AOJ

# # Problem

http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=CGL_2_B

Determin if 2 segments intersect each other.

# # Solution

Define the return value of function cw

1. 1: Counter-clockwise
2. -1: Clockwise
3. 0: On segment
4. other integer $x$: on a line, but out of segment

The result of the product of the 2 cw means:

1. 1: no intersection.
2. -1: They intersect.
3. 0: They intersect. 4 points on a line. Either vertex of segment is on the other segment
4. $x^2$: no intersection. 4 points on a line, but no common part.
Int N;
Vector2 p0, p1, p2, p3;

int cw(Vector2 v01, Vector2 v02) {
double cross_ = v01.cross(v02);
if (cross_ > EPS) return 1; // above segment
else if (cross_ < -EPS) return -1; // beneath segment
if (v01.dot(v02) < 0) return 2; // opposite
if (v01.length() - v02.length() >= 0) return 0; // on segment
return -2; // out of segment
}

void solve() {
int cw1 = cw(p1 - p0, p2 - p0) * cw(p1 - p0, p3 - p0);
int cw2 = cw(p3 - p2, p1 - p2) * cw(p3 - p2, p0 - p2);
if (cw1 <= 0 && cw2 <= 0) cout << 1 << endl;
else cout << 0 << endl;
}

void input() {
cin >> N;
while (cin >> p0 >> p1 >> p2 >> p3) {
solve();
}
}

int main() {
cout.precision(15);
input();
}


Remote freelancer. A web and mobile application enginner.
Traveling around the world based on East Asia.
I'm looking forward to your job offers from all over the world!

Offer jobs or contact me!