//Javrvis算法计算凸包的周长
//#include "stdafx.h"
#include<iostream>
#include<algorithm>
#include<cmath>
#define size 1010
using namespace std;
struct point {
int x;
int y;
};
point spot[size];
int n, cnt, tail;
int tubao[size], start[size];
bool cmp(point a, point b) {
return (a.y < b.y || a.y == b.y && a.x < b.x);
}
//判断是否严格左转,共线不算左转
bool CrossLeft(point p1, point p2, point p3) {
return ((p3.x - p1.x) * (p2.y - p1.y) - (p2.x - p1.x) * (p3.y - p1.y)) < 0;
}
void Jarvis() {
tail = cnt = 0;
sort(spot, spot + n, cmp);
start[tail++] = 0, start[tail++] = 1;
for (int i = 2; i < n; i++) {
while (tail > 1 && !CrossLeft(spot[start[tail - 1]], spot[start[tail - 2]], spot[i]))
tail--;
start[tail++] = i;
}
for (int i = 0; i < tail; i++) tubao[cnt++] = start[i];
tail = 0; start[tail++] = n - 1; start[tail++] = n - 2;
for (int i = n - 3; i >= 0; i--) {
while (tail > 1 && !CrossLeft(spot[start[tail - 1]], spot[start[tail - 2]], spot[i]))
tail--;
start[tail++] = i;
}
for (int i = 0; i < tail; i++)
tubao[cnt++] = start[i];
}
int main()
{
//输入n个点
cin >> n ;
for (int i = 0; i < n; i++)
cin >> spot[i].x >> spot[i].y;
//调用凸包的Javrvis算法
Jarvis();//tubao[]为求得的凸包中的点
double length = 0;
///计算凸包的周长
for (int i = 0; i < cnt - 1; i++)
length += sqrt(pow((spot[tubao[i]].x - spot[tubao[i + 1]].x),2) + pow((spot[tubao[i]].y - spot[tubao[i + 1]].y),2) * 1.0);
cout << length << endl;
return 0;
}
Javrvis算法计算凸包的周长
最新推荐文章于 2021-02-27 08:50:31 发布