其他分享
首页 > 其他分享> > 凸包模板

凸包模板

作者:互联网

#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdio>
#include<cmath>
#define x first
#define y second
using namespace std;
const int N = 110;
typedef pair<int,int> PII;
int n;
PII d[N];
int stk[N],top;
bool cmp(PII a,PII b){
    int x0 = d[1].x,y0 = d[1].y;
    int ax = a.x - x0,ay = a.y - y0;
    int bx = b.x - x0,by = b.y - y0;
    int val = ax * by - ay * bx;
    if(val > 0) return true;
    return false;
}
double getLen(int a,int b){
    int ax = d[a].x,ay = d[a].y;
    int bx = d[b].x,by = d[b].y;
    return sqrt(1.0 * (ax - bx) * (ax - bx) + (ay - by) * (ay - by));
}
int main(){
    while(cin >> n,n){
        top = 0;
        for(int i = 1;i <= n;i ++){
            int a,b;
            cin >> a >> b;
            d[i] = {a,b};
        }
        int idx = 1;
        for(int i = 1;i <= n;i ++){
            if(d[i].y < d[idx].y)
                idx = i;
        }
        swap(d[1],d[idx]);
        sort(d + 2,d + 1 + n,cmp);
        d[n + 1] = d[1];
        double ans = 0;
        stk[++ top] = 1;
        stk[++ top] = 2;
        for(int i = 3;i <= n + 1;i ++){
            while(top > 1){
                int a = stk[top],b = stk[top - 1];
                int ax = d[a].x - d[b].x,ay = d[a].y - d[b].y;
                int bx = d[i].x - d[b].x,by = d[i].y - d[b].y;
                if(ax * by - bx * ay < 0){
                    top --;
                }
                else
                    break;
            }
            stk[++ top] = i;
        }
        for(int i = 2;i <= top;i ++){
            ans += getLen(stk[i - 1],stk[i]);
        }
        if(n == 2) ans = getLen(1,2);
        printf("%.2lf\n",ans);
    }
    return 0;
}

作者:正在加载中...
链接:https://www.acwing.com/blog/content/15028/
来源:AcWing
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
``

标签:int,top,凸包,ay,ax,include,bx,模板
来源: https://www.cnblogs.com/sherkevin/p/16182185.html