summaryrefslogtreecommitdiff
path: root/geometry/segmentIntersection.cpp
blob: b2e3ac445ab6ff8a9f7c2d1515e5176a3c9d010b (plain)
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
struct seg {
	pt a, b;
	int id;
	bool operator<(const seg& o) const {
		if (real(a) < real(o.a)) {
			int s = orientation(a, b, o.a);
			return (s > 0 || (s == 0 && imag(a) < imag(o.a)));
		} else if (real(a) > real(o.a)) {
			int s = orientation(o.a, o.b, a);
			return (s < 0 || (s == 0 && imag(a) < imag(o.a)));
		}
		return imag(a) < imag(o.a);
	}
};
 
struct event {
	pt p;
	int id, type;
	bool operator<(const event& o) const {
		if (real(p) != real(o.p)) return real(p) < real(o.p);
		if (type != o.type) return type > o.type;
		return imag(p) < imag(o.p);
	}
};
 
bool lessPT(const pt& a, const pt& b) {
	return real(a) != real(b) ? real(a) < real(b)
	                          : imag(a) < imag(b);
}
 
bool intersect(const seg& a, const seg& b) {
	return lineSegmentIntersection(a.a, a.b, b.a, b.b);
}
 
pair<int, int> intersect(vector<seg>& segs) {
	vector<event> events;
	for (seg& s : segs) {
		if (lessPT(s.b, s.a)) swap(s.b, s.a);
		events.push_back({s.a, s.id, 1});
		events.push_back({s.b, s.id, -1});
	}
	sort(all(events));
 
	set<seg> q;
	vector<set<seg>::iterator> where(sz(segs));
	for (auto e : events) {
		int id = e.id;
		if (e.type > 0) {
			auto it = q.lower_bound(segs[id]);
			if (it != q.end() && intersect(*it, segs[id]))
				return {it->id, segs[id].id};
			if (it != q.begin() && intersect(*prev(it), segs[id]))
				return {prev(it)->id, segs[id].id};
			where[id] = q.insert(it, segs[id]);
		} else {
			auto it = where[id];
			if (it != q.begin() && next(it) != q.end() && intersect(*next(it), *prev(it)))
				return {next(it)->id, prev(it)->id};
			q.erase(it);
		}
	}
	return {-1, -1};
}