-
Notifications
You must be signed in to change notification settings - Fork 1
/
ConvexHull
62 lines (61 loc) · 1.45 KB
/
ConvexHull
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
#include <stdio.h>
#include <algorithm>
#include <math.h>
#include <vector>
using namespace std;
struct pp{
int x,y,dis;
double angle;
pp(){}
pp(int a,int b){
x=a; y=b;
}
bool operator()(pp i, pp j){
return i.y < j.y;
}
bool operator<(const pp &q)const{
return angle < q.angle || (angle==q.angle && dis < q.dis);
}
};
struct ConvexHull{
private:
vector<pp> v, ret;
int n;
int ccw(pp a,pp b,pp c){
int t = (b.x-a.x)*(c.y-a.y) - (b.y-a.y)*(c.x-a.x);
if (t>0) return 1;
else if (t<0) return -1;
else return 0;
}
void calc(){
sort(v.begin(),v.end(),pp());
v[0].angle = -10000;
int i;
for (i=1;i<n;i++){
v[i].angle = atan2(v[i].y-v[0].y,v[i].x-v[0].x);
v[i].dis = (v[i].y-v[0].y)*(v[i].y-v[0].y) + (v[i].x-v[0].x)*(v[i].x-v[0].x);
}
sort(v.begin(),v.end());
ret.push_back(v[0]);
ret.push_back(v[1]);
for (i=2;i<n;i++){
while(ret.size()>1){
int t = ccw(ret[ret.size()-1],ret[ret.size()-2],v[i]);
if (t<=0) ret.pop_back();
else break;
}
ret.push_back(v[i]);
}
}
public:
ConvexHull(){};
ConvexHull(vector<pp> _input) {
v.clear(); ret.clear();
v = _input;
n = (int)v.size();
calc();
}
vector<pp> result() {
return ret;
}
};