Do the Segments Cross?

easy geometry math 2000 ms · 256 MB

Do the Segments Cross?

You are given two closed line segments in the plane, each given by its two integer endpoints. A closed segment includes its endpoints, so if the segments merely touch — at a shared endpoint, at a point where one segment's endpoint lands in the middle of the other, or along a shared stretch when the two segments are collinear — that counts as sharing a point.

A segment may be degenerate: both of its endpoints can coincide, in which case the segment is just a single point.

For each of several independent test cases, decide whether the two given segments share at least one point.

Input

The first line contains an integer T (1 ≤ T ≤ 10^5) — the number of test cases.

Each of the next T lines contains eight integers

x1 y1 x2 y2 x3 y3 x4 y4

with -10^9 ≤ x1, y1, x2, y2, x3, y3, x4, y4 ≤ 10^9, describing segment A with endpoints (x1, y1) and (x2, y2), and segment B with endpoints (x3, y3) and (x4, y4). The two endpoints of a segment are not guaranteed to be distinct.

Output

For each test case, print YES if segments A and B share at least one point, and NO otherwise, each on its own line.

Notes

In the first example, the first test case's segments cross in their interiors, the second pair only touch at a shared endpoint, and the third pair are parallel and never meet — all three still count the touching case as YES.

Coordinates are large enough (up to 10^9 in absolute value) that products of coordinate differences can reach about 4·10^18 in magnitude, so floating-point arithmetic is not precise enough: use exact integer (64-bit) arithmetic throughout.

Example 1

Input

3
0 0 4 4 0 4 4 0
0 0 4 4 4 4 8 0
0 0 4 4 0 1 4 5

Output

YES
YES
NO

Example 2

Input

3
0 0 10 0 5 0 15 0
0 0 10 0 20 0 30 0
3 3 3 3 0 0 6 6

Output

YES
NO
YES

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

Hint 1

Think about which side of a line each endpoint of one segment lies on. What does a zero cross product tell you, and when is that not enough to decide whether the segments meet?

Hint 2

Use the sign of the cross product, computed exactly in 64-bit integers, to check whether each segment's endpoints lie on opposite sides of the other segment's line. Handle the zero-orientation cases separately with a bounding-box check, which also covers single-point segments.

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

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