The Demon King's Castle
InterviewTime limit3sMemory limit1024 MB
For each plot, find the total tax of the connected region of plots no higher than it that contains that plot, with the plot as the castle.
- Level
Medium5 of 10
- Topics
- Union-find, Sorting, Matrix
- Solved
- No attempts yet
Problem
A Demon King with ambitions of conquering the world has decided to found his own nation! But before he can form a nation, he has many things to do, such as choosing territory and building a castle.
The site that can become territory is an rectangle divided into plots of land. The Demon King selects one or more plots and declares them his territory, then builds his castle on one of those plots. Each plot has two values: its "height" and the "tax it yields." The figure below shows the tax and height of each plot in Sample 2.

The Demon King values communication with his people, so every plot in the territory must be able to reach the castle by moving through adjacent territory plots up, down, left, or right. He also firmly believes he must be the highest person in the world, so the plot with the castle must be at least as high as every other plot in the territory.
The total tax the Demon King collects equals the sum of the taxes of all plots in the territory. He wants to know the maximum tax he can collect for each of the plots as the castle location. He cannot program, so you, captured by the Demon King, must write a program to solve this.
Input
The first line contains and , separated by a space.
The next lines each contain heights of the plots, separated by spaces.
The following lines each contain taxes of the plots, separated by spaces.
Output
Print lines, each with integers separated by spaces. The -th number on the -th line is the maximum total tax when the castle is built on plot .
Constraints