Truffles
Time limit3sMemory limit128 MB
Given a grid of per-meter values, compute for each of M slanted lines the weighted length integral of the line through the grid, rounded to five decimals.
- Level
Hard8 of 10
- Topics
- Geometry, Prefix sum, Math
- Solved
- No attempts yet
Problem
Near Mirko's village there is a forest where passers-by often find truffles. The forest is a square with side length meters. The center of the square is at the origin of the coordinate system, and its sides are parallel to the coordinate axes.
The square is divided into equal regions, each a square with side length 1 meter. For each region, you know how many grams of truffles someone finds by walking one meter inside that region.

The figure shows the sample.
Mirko plans to take walks. On each walk, Mirko picks a line that is not parallel to either coordinate axis and walks along that line.
For each walk, print the total number of grams of truffles Mirko finds on that walk. This total is the sum, over every region inside the forest, of the length of the line inside that region multiplied by the region's value. If the line passes through only a single corner point of a region, the length walked in that region is 0.
Input
The first line contains an integer (), half the side length of the forest.
Each of the next lines contains characters from 1 to 9. Each character is the number of grams of truffles found per meter walked in that region. The regions are listed from north to south (in decreasing order of the coordinate), and within a line from west to east (in increasing order of the coordinate), as in the figure above.
The next line contains an integer (), the number of walks.
Each of the next lines contains four integers , , , and : the coordinates of two different points and on the line Mirko walks along.
It holds that , , and .
Output
Print real numbers, one per line. The -th number is the total number of grams of truffles Mirko finds on the -th walk.
Round each exact value to exactly five digits after the decimal point. If the exact value lies exactly halfway between two candidates, round up. For example, print 0 as 0.00000.