Javrvis算法计算凸包的周长

来源:互联网 发布:香港买mac口红多少钱 编辑:程序博客网 时间:2024/05/17 07:22
//Javrvis算法计算凸包的周长//#include "stdafx.h"#include<iostream>#include<algorithm>#include<cmath>#define size 1010using 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;}