Two Windows on the Screen

easy geometry math 1000 ms · 256 MB

Two Windows on the Screen

You're building a window manager that reports how much of the screen is covered by windows, for a compositor that only ever has at most two windows open at once. Each window is an axis-aligned rectangle, given by two opposite corners in pixel coordinates — but the corners for a given window are not guaranteed to come in any particular order (either corner may be the top-left, bottom-left, and so on).

For each query, you're given both windows. Report the total number of pixels covered by at least one of them — the area of their union. Windows may touch, overlap, nest inside one another, coincide exactly, or be degenerate (a window whose two corners share an x or a y coordinate has zero area, like a line or a single point drawn on the screen).

Input

The first line contains an integer q (1 ≤ q ≤ 10^5) — the number of queries.

Each of the next q lines describes one query with eight integers:

x1 y1 x2 y2 x3 y3 x4 y4

(x1, y1) and (x2, y2) are two opposite corners of the first window, and (x3, y3) and (x4, y4) are two opposite corners of the second window. Every coordinate satisfies 0 ≤ coordinate ≤ 10^9. Within a window the two given corners are not necessarily ordered (you may have x1 > x2 or y1 > y2, and likewise for the second window).

Output

For each query, print a single integer on its own line: the area of the union of the two windows, in pixels.

Notes

If the two windows don't overlap in x or don't overlap in y (including when they merely touch along an edge with zero-width overlap), the overlap area is zero and the answer is simply the sum of the two windows' areas.

Example 1

Input

3
0 0 4 4 2 2 6 6
0 0 2 2 2 0 4 2
0 0 10 10 2 2 5 5

Output

28
8
100

Example 2

Input

4
5 5 1 1 1 5 5 1
3 3 3 7 0 0 10 10
1000000000 1000000000 0 0 0 0 1000000000 1000000000
0 0 0 0 0 0 0 0

Output

16
100
1000000000000000000
0

Hints · reveal one at a time if you're stuck

Hint 1

The corners can come in any order, so first normalise each window to its lowest and highest x and y. Then the union area is the sum of the two areas minus the area they share.

Hint 2

The shared region is itself a rectangle, so think about its width and height separately. What happens to those two numbers when the windows are disjoint or only touch, and why must you handle that before multiplying?

report an issue Prefer your own editor? sooks prep 82 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.