题目地址:http://poj.org/problem?id=2007
解题思路:
每个点都和(0,0)点连接,构成一个向量,逆时针排序这些向量的极角逐渐增大。用atan2求解误差较大,会wa(;´༎ຶД༎ຶ`)舍弃该方法
排完序后的点集,任取相邻两个点A(在前),B(在后),定有Cross(A,B)>0,故cmp函数可写成:
bool cmp(Point A, Point B) { return Cross(A,B) > 0; }
注意:此方法只适用于凸多边形,故也可用求凸包的方法解这道题,代码略。
ac代码:
极角排序
#include <iostream>
#include <cmath>
#include <vector>
#include <algorithm>
using namespace std;
typedef long long ll;
const double eps = 1e-8;
const double pi = acos(-1.0);
const int maxn = 1000;
int dcmp(double x)
{
if(fabs(x) < eps) return 0;
else return x > 0 ? 1 : -1;
}
struct Point
{
double x,y;
Point(int x=0, int y=0):x(x),y(y){}
};
typedef Point Vector;
double Cross(Vector a, Vector b)//外积
{
return a.x * b.y - a.y * b.x;
}
bool cmp(Point A, Point B)
{
return Cross(A,B) > 0;
}
int n = 0;
Point p[maxn];
int main()
{
//freopen("/Users/zhangkanqi/Desktop/11.txt","r",stdin);
while(~scanf("%lf %lf",&p[n].x, &p[n].y)) n++;
sort(p+1, p+n, cmp);
for(int i = 0; i < n; i++)
{
printf("(%d,%d)\n", (int)p[i].x, (int)p[i].y);
}
return 0;
}