Bajhattan Panorama
Time limit1sMemory limit128 MB
Given row maxima and column maxima, test whether any grid fits them and compute the largest possible total height.
- Level
Medium6 of 10
- Topics
- Greedy, Sorting, Prefix sum
- Solved
- No attempts yet
Problem
Bajtek is about to take his first ever trip overseas, to the United States of Byteotia. What he most wants to see is Bajhattan, a district of one of the huge cities there. Bajhattan is full of tall skyscrapers, and its panorama (the view of the buildings from far away) is famous.
Bajhattan consists of blocks. Each block is either empty or occupied by exactly one skyscraper of some height. For simplicity, an empty block is treated as a block holding a skyscraper of height . The streets between blocks are ignored. For example, take , and skyscraper heights as in the table below (a bird's-eye view, with north at the top of the table):
Then Bajhattan looks like the picture below:

Bajtek has only ever seen Bajhattan in photos. The two most famous panoramas are the western one and the southern one. In the example above, the western panorama is dominated by skyscrapers of heights 3, 2 and 2, while the southern panorama shows skyscrapers of heights 2, 2, 1 and 3. The photos were taken from quite far away, so only the outlines of the buildings are visible.
In other words, the -th value of the western panorama is the height of the tallest skyscraper in the -th row (counting rows from north to south), and the -th value of the southern panorama is the height of the tallest skyscraper in the -th column (counting columns from west to east).
For the example layout, the western panorama looks like this:

And here is the southern panorama:

From these photos alone, Bajtek would like to work out how large the skyscrapers of Bajhattan are. He wants to estimate their total volume.
Help him: report the maximum possible total volume of all the skyscrapers of Bajhattan. In the example the actual total volume is 14, but if the layout were slightly different (while the panoramas stayed the same), the volume could be as large as 22.
Input
The first line contains two integers and (). The second line contains integers (): the heights of the skyscrapers in the western panorama, listed from the northernmost. The third line contains integers (): the heights of the skyscrapers in the southern panorama, listed from the westernmost. You may assume that .
Output
Print the maximum possible total volume of Bajhattan on one line. If Bajtek made a mistake (for example by mixing one panorama of Bajhattan with one of San Bajcisko, which he also visits) and the two photos cannot depict the same city, print the single word NIE instead.