Under construction

Still being built. Things may change

Truffles

Time limit3sMemory limit128 MB

Summary
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 2N2N 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 2N×2N2N \times 2N 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 MM 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 NN (1≤N≤5001 \le N \le 500), half the side length of the forest.

Each of the next 2N2N lines contains 2N2N 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 yy coordinate), and within a line from west to east (in increasing order of the xx coordinate), as in the figure above.

The next line contains an integer MM (1≤M≤20001 \le M \le 2000), the number of walks.

Each of the next MM lines contains four integers x1x_1, y1y_1, x2x_2, and y2y_2: the coordinates of two different points (x1,y1)(x_1, y_1) and (x2,y2)(x_2, y_2) on the line Mirko walks along.

It holds that −10000≤x1,y1,x2,y2≤10000-10000 \le x_1, y_1, x_2, y_2 \le 10000, x1≠x2x_1 \ne x_2, and y1≠y2y_1 \ne y_2.

Output

Print MM real numbers, one per line. The ii-th number is the total number of grams of truffles Mirko finds on the ii-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.

Examples1

  1. Example 1

    Input
    2
    1357
    2468
    1111
    9999
    4
    0 0 1 1
    -3 0 0 3
    -2 0 2 -1
    2 -4 4 2
    
    Expected output
    32.52691
    1.41421
    4.12311
    0.00000