1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| #include <iostream> #include <algorithm> using namespace std; struct line { pair<int,int> a, b; }; int ccw(pair<int, int> a, pair<int, int> b, pair<int, int> c) { int op = a.first * b.second + b.first * c.second + c.first * a.second - (a.second * b.first + b.second * c.first + c.second * a.first); return op > 0 ? 1 : !op ? 0 : -1; } bool isIntersect(line l1, line l2) { if(l1.a == l2.a || l1.a == l2.b || l1.b == l2.a || l1.b == l2.b) return true; int ab = ccw(l1.a, l1.b, l2.a) * ccw(l1.a, l1.b, l2.b); int cd = ccw(l2.a, l2.b, l1.a) * ccw(l2.a, l2.b, l1.b); if(!ab && !cd) { if(l1.a > l1.b) swap(l1.a, l1.b); if(l2.a > l2.b) swap(l2.a, l2.b); return l2.a <= l1.b && l1.a <= l2.b; } return ab <= 0 && cd <= 0; } int main() { line line1 = line{.a.first = 1, .a.second = 1, .b.first = 3, .b.second = 3}; line line2 = line{.a.first = 1, .a.second = 2, .b.first = 3, .b.second = 4}; line line3 = line{.a.first = 1, .a.second = 2, .b.first = 3, .b.second = 3}; printf("%s\n", isIntersect(line1, line2) ? "cross" : "non-cross"); printf("%s\n", isIntersect(line1, line3) ? "cross" : "non-cross"); printf("%s\n", isIntersect(line2, line3) ? "cross" : "non-cross"); }
|