-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathline_sweep.cpp
More file actions
105 lines (86 loc) · 2.37 KB
/
Copy pathline_sweep.cpp
File metadata and controls
105 lines (86 loc) · 2.37 KB
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#include <bits/stdc++.h>
using namespace std;
const double EPS = 1E-9;
struct pt {
double x, y;
};
struct seg {
pt p, q;
int id;
double get_y (double x) const {
if (abs (p.x - q.x) < EPS) return p.y;
return p.y + (q.y - p.y) * (x - p.x) / (q.x - p.x);
}
};
inline bool intersect1d (double l1, double r1, double l2, double r2) {
if (l1 > r1) swap (l1, r1);
if (l2 > r2) swap (l2, r2);
return max (l1, l2) <= min (r1, r2) + EPS;
}
inline int vec (const pt & a, const pt & b, const pt & c) {
double s = (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);
return abs(s)<EPS ? 0 : s>0 ? +1 : -1;
}
bool intersect (const seg & a, const seg & b) {
return intersect1d (a.p.x, a.q.x, b.p.x, b.q.x)
&& intersect1d (a.p.y, a.q.y, b.p.y, b.q.y)
&& vec (a.p, a.q, b.p) * vec (a.p, a.q, b.q) <= 0
&& vec (b.p, b.q, a.p) * vec (b.p, b.q, a.q) <= 0;
}
bool operator< (const seg & a, const seg & b) {
double x = max (min (a.p.x, a.q.x), min (b.p.x, b.q.x));
return a.get_y(x) < b.get_y(x) - EPS;
}
struct event {
double x;
int tp, id;
event() { }
event (double x, int tp, int id)
: x(x), tp(tp), id(id)
{ }
bool operator< (const event & e) const {
if (abs (x - e.x) > EPS) return x < e.x;
return tp > e.tp;
}
};
set<seg> s;
vector < set<seg>::iterator > where;
inline set<seg>::iterator prev (set<seg>::iterator it) {
return it == s.begin() ? s.end() : --it;
}
inline set<seg>::iterator next (set<seg>::iterator it) {
return ++it;
}
pair<int,int> solve (const vector<seg> & a) {
int n = (int) a.size();
vector<event> e;
for (int i=0; i<n; ++i) {
e.push_back (event (min (a[i].p.x, a[i].q.x), +1, i));
e.push_back (event (max (a[i].p.x, a[i].q.x), -1, i));
}
sort (e.begin(), e.end());
s.clear();
where.resize (a.size());
for (size_t i=0; i<e.size(); ++i) {
int id = e[i].id;
if (e[i].tp == +1) {
set<seg>::iterator
nxt = s.lower_bound (a[id]),
prv = prev (nxt);
if (nxt != s.end() && intersect (*nxt, a[id]))
return make_pair (nxt->id, id);
if (prv != s.end() && intersect (*prv, a[id]))
return make_pair (prv->id, id);
where[id] = s.insert (nxt, a[id]);
}
else {
set<seg>::iterator
nxt = next (where[id]),
prv = prev (where[id]);
if (nxt != s.end() && prv != s.end() && intersect (*nxt, *prv))
return make_pair (prv->id, nxt->id);
s.erase (where[id]);
}
}
return make_pair (-1, -1);
}