Fishing
Time limit10sMemory limit1024 MB
Given K weighted cells in an N by M grid, answer online queries for the maximum sum of a contiguous column block within columns X to Y over the first H rows.
- Level
Medium7 of 10
- Topics
- Segment tree, Prefix sum, Dynamic programming
- Solved
- No attempts yet
Statement
There is a small village on the coast of the Adriatic Sea. The fishermen map the sea as a grid of cells. The first row is adjacent to the coast, and the last row is the farthest away. They track the movement of fish and other items floating in the sea. Most of the sea is empty, but there are cells of interest. The location of the -th cell is row and column . The fishermen estimate that their catch from fishing in the -th cell is worth . can be zero or negative if that area is mostly occupied by undesired items. All other cells have a value of .
Every day, the local council approves a rectangular fishing area that includes columns from to and extends rows from the shore into the sea. To fish in the selected area, the fishermen prepare a fishing net exactly units long. The net has a fixed length, but it can be rolled out to any width up to . Based on what they know about the sea, the fishermen drop the net somewhere within the approved area so that the sum of the cell values it covers is as large as possible.
Write a program that finds the best catch for the approved fishing areas over the next days. Cell values stay constant. Fishing on earlier days does not deplete them.
Input
The first line contains the number of rows , the number of columns , and the number of non-empty cells . Each of the next lines gives the row , column , and value of one cell, separated by spaces. Rows are numbered from 1 to , and columns from 1 to . All are integers.
The next line contains the number of queries . The -th query is given as three integers , , and . The queries are encoded so that your program must answer them in the given order. The actual query is computed as follows.
Here is the answer to the -th query, and is when . denotes bitwise XOR. Your program must find the region with the maximum catch value that spans the first rows and some subrange of columns from to .
Output
For each query, output the maximum catch value on its own line. The fishermen can always keep an empty net, which has a value of .
Constraints
Hint
The decoded list of queries:
5 1 5
10 1 7
7 6 6
8 2 6
4 1 6
3 1 2