跳到正文

剪贴板

剪贴板 z1co0m9d

TheChariot
原文
剪贴板信息

剪贴板信息

发布
收录
更新

P2742 凸包(graham算法)

C++
#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int N=1e5+5;
struct node{
	double x,y,ag;
}p[N];
int n;
double _=0;
double dist(node x,node y){
	return sqrtl((x.x-y.x)*(x.x-y.x)+(x.y-y.y)*(x.y-y.y));
}
double cross(node a,node b){
	return a.x*b.y-a.y*b.x;
}
bool cmp(node x,node y){
	if(x.ag!=y.ag) return x.ag<y.ag;
	return dist(x,p[1])<dist(y,p[1]);
}
stack<node>st;
double ans;
int main(){
	scanf("%d",&n);
	for(int i=1;i<=n;i++){
		scanf("%lf%lf",&p[i].x,&p[i].y);
		if(p[i].y<p[1].y||(p[i].y==p[1].y&&p[i].x<p[1].x)) swap(p[i],p[1]);
	}
	for(int i=2;i<=n;i++){
		p[i].ag=atan2(p[i].y-p[1].y,p[i].x-p[1].x);
	}
	sort(p+2,p+n+1,cmp);
	st.push(p[1]);
	for(int i=2;i<=n;i++){
		while(st.size()>1){
			node las1=st.top();st.pop();
			node las2=st.top();
			node x,y;
			x.x=las1.x-las2.x,x.y=las1.y-las2.y;
			y.x=p[i].x-las1.x,y.y=p[i].y-las1.y;
			if(cross(x,y)>_){
				st.push(las1);
				break;
			}
		}
		st.push(p[i]);
	}
	node las=p[1];
	while(st.size()){
		ans+=dist(las,st.top());
		las=st.top();st.pop();
	}
	printf("%.2lf",ans);
	return 0;
}