This repository has been archived by the owner on Oct 29, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 178
/
Copy pathConvexHull_MonotoneChain.cpp
89 lines (81 loc) · 1.76 KB
/
ConvexHull_MonotoneChain.cpp
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
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define pii pair<int,int>
#define PB push_back
#define MP make_pair
#define F first
#define S second
vector< pii > vp,upper,lower;
int n;
void display(){ for(int i=0;i<vp.size();i++) cout<<vp[i].F<<" "<<vp[i].S<<endl; }
int cross(pii p1, pii p2)
{
int temp = p1.F*p2.S - p1.S*p2.F;
if(temp==0)
return 0;
if(temp>0)
return 1;
return -1;
}
pii vect(pii p1, pii p2)
{
pii p = MP(p1.F-p2.F, p1.S-p2.S);
return p;
}
int main()
{
int x,y,h;
pii p;
cin>>n;
for(int i=0;i<n;i++)
{
cin>>x>>y;
vp.PB(MP(x,y));
}
sort(vp.begin(),vp.end());
//upper layer formation
upper.PB(vp[0]);
h=0;
for(int i=1;i<n;i++)
{
p = vp[i];
upper.PB(p);
h++;
while(upper.size()>2 && cross(vect(upper[h-1],upper[h-2]),vect(upper[h],upper[h-1]))>=0)
{
upper.pop_back();
upper.pop_back();
upper.PB(p);
h--;
}
}
//lower layer formation
lower.PB(vp[n-1]);
h=0;
for(int i=n-2;i>=0;i--)
{
p = vp[i];
lower.PB(p);
h++;
while(lower.size()>2 && cross(vect(lower[h-1],lower[h-2]),vect(lower[h],lower[h-1]))>=0)
{
lower.pop_back();
lower.pop_back();
lower.PB(p);
h--;
}
}
//printing points of convex hull
cout<<"Points of convex hull starting from lower bottom point in a clockwise order: ";
for(int i=0;i<int(upper.size())-1;i++)
{
cout<<"("<<upper[i].F<<","<<upper[i].S<<") ";
}
for(int i=0;i<int(lower.size())-1;i++)
{
cout<<"("<<lower[i].F<<","<<lower[i].S<<") ";
}
cout<<endl;
return 0;
}