洛谷P2742 圈奶牛Fencing the Cows(凸包模板)

題目鏈接

https://www.luogu.org/problem/P2742

代碼

#include <bits/stdc++.h>
#define ll long long
using namespace std;
const ll maxn=1e4+10;
int inf=1e9;
void read(int &x){
    int f=1;x=0;char s=getchar();
    while(s<'0'||s>'9'){if(s=='-')f=-1;s=getchar();}
    while(s>='0'&&s<='9'){x=x*10+s-'0';s=getchar();}
    x*=f;
}
struct node{
	double x,y;
};

node p[maxn],s[maxn];//s存儲凸包 
double xx,yy;    //極點 
//向量ab,向量ac 叉積 
double compare(node a,node b,node c){
    return (b.x-a.x)*(c.y-a.y)-(c.x-a.x)*(b.y-a.y);
}
//極角排序 
bool cmp(node a,node b){
    node c;
    c.x=xx;
    c.y=yy;
    if(compare(c,a,b)==0)
        return a.x<b.x;
    else
        return compare(c,a,b)>0;
}

//求邊長 
double bian(node a,node b){
    return sqrt((a.x-b.x)*(a.x-b.x)+(b.y-a.y)*(b.y-a.y));
}
int n;
void tubao(){
	int k,top=1;
	yy=inf;
	for(int i=0;i<n;i++){
		if(yy>p[i].y){
			yy=p[i].y;
			xx=p[i].x;
			k=i;
		}
	}
	p[k]=p[0];
	sort(p+1,p+n,cmp);
	s[0].x=xx;
    s[0].y=yy;
    s[1]=p[1];
    for(int i=2;i<n;){
        if(top&&(compare(s[top-1],s[top],p[i])<0))
            top--;
        else
            s[++top]=p[i++];
    }
    /*
    double ans1=0;
	for(int i=0;i<=top;i++)    //遍歷求構成三角形最大的面積
        for(int j=i+1;j<=top;j++)
            for(int k=j+1;k<=top;k++)
               ans1=max(ans1,compare(s[j],s[k],s[i]));
        
	printf("%.2lf\n",0.5*ans1);
	*/
	double  ans[maxn];   // 求凸多邊形周長
    s[++top]=s[0];
    for(int i=0; i<top; i++)
        ans[i]=bian(s[i],s[i+1]);
    double sum=0;
    for(int i=0; i<top; i++){
        sum+=ans[i];
    }
	printf("%.2lf\n",sum);
} 

int main(){
	int i;
	read(n);
	for(i=0;i<n;i++){
		scanf("%lf%lf",&p[i].x,&p[i].y);
	}
	tubao();
    return 0;
}

 

發佈了37 篇原創文章 · 獲贊 11 · 訪問量 4786
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章