您的位置:首页 > 其它

【解题报告】 NYOJ 78 -- 圈水池 Andrew 凸包算法

2012-09-06 10:11 597 查看
题目连接: NYOJ 78凸包入门水题

不会凸包的移步这里

// NYOJ 78 -- 圈水池 Andrew 凸包算法 O(nlogn)
// 将凸包的顶点按 从小到大 先x后y的 顺序输出
//
/*test data
9 100
200 400
300 400
300 300
400 300
400 400
500 400
500 200
350 200
200 200
== 1628

*/

#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;

const int MAXP = 1010;
const double Pzero = 0.00001;

struct POINT{
int x,y;
}p[MAXP],CHp[MAXP*2];

double XJ(POINT a, POINT b, POINT c){
// vector a->b (b.x-a.x, b.y-a.y)
// vector a->c (c.x-a.x, c.y-a.y)
return (b.x-a.x)*(c.y-a.y) - (c.x-a.x)*(b.y-a.y);
}

bool comp(POINT a,POINT b){
return (a.x < b.x) || ((a.x==b.x) && (a.y<b.y));
}

int AndrewConvexHull(POINT *CHp, int n){
// 计算凸包 CHp[] 逆时针存点
sort(p, p + n, comp);
int nCHp = 0;
for (int i = 0 ; i < n ; CHp[nCHp++] = p[i++])
while(nCHp >= 2 && XJ(CHp[nCHp-2], CHp[nCHp-1], p[i]) <= 0)
nCHp--;
for (int i = n - 1,m = nCHp + 1 ; i >= 0 ; CHp[nCHp++] = p[i--])
while(nCHp >= m && XJ(CHp[nCHp-2], CHp[nCHp-1], p[i]) <= 0)
nCHp--;
return --nCHp;
}

void init(int n){
// 输入
for (int i = 0 ; i < n; i++)
scanf("%d%d", &p[i].x, &p[i].y);
}

void Output(int nCHp){
sort(CHp, CHp + nCHp, comp);
for (int i = 0; i < nCHp ; i++){
printf("%d %d\n", CHp[i].x, CHp[i].y);
}
}

int main()
{
//	freopen("in.txt","r",stdin);
int n;scanf("%d",&n);
while(~scanf("%d",&n) ){

init(n);
int nCHp = AndrewConvexHull(CHp, n);
Output(nCHp);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: