POJ 1696 Space Ant

数据小 暴力极角排序

先把最下面的一个点放在第一位 这样乃至以后的计算 极角都是在0~Pi 范围内的

每次排序后的第一个点一定是最优的

/*
首先 一定能把所有点都走完
其次是如何走 我们先选择一个x最小的开始
每次走到了v 就以v为极点 对于剩余的点进行极角排序 选择极角最小的点走
*/
#include<cmath>
#include<cstdio>
#include<algorithm>
using namespace std;
const int N=150;
const double eps=1e-9;
struct Point
{
    int id; double x,y;
}p[N];
int T,n,op;
double operator * (Point A,Point B) {return A.x*B.x+A.y*B.y;} 
double operator ^ (Point A,Point B) {return A.x*B.y-A.y*B.x;} 
Point operator -(Point a,Point b)
{
    Point c;c.x=a.x-b.x;c.y=a.y-b.y;return c;
}
double dist(Point a,Point b)
{
    return sqrt((a-b)*(a-b));
}
bool cmp(Point a,Point b)
{
    double c=(a-p[op])^(b-p[op]);
// 这里a,b都减去了p[op] a,b相对位置不变 但是让极点从 p[op]变为了 (0,0)
// 就可以进行正常的极角排序了 
    if(fabs(c)<=eps) return dist(a,p[op])<dist(b,p[op]);
// 不同的是如果极角相等 肯定就走较近的一个(而不是x较小在前) 因为不能反方向走 
    return c>eps;
}
int main()
{
    scanf("%d",&T);while(T--)
    {
        scanf("%d",&n);
        for(int i=1;i<=n;i++) 
        {
            scanf("%d%lf%lf",&p[i].id,&p[i].x,&p[i].y);
            if(p[i].y<p[1].y||(p[i].y==p[1].y&&p[i].x<p[1].x))
                        swap(p[1],p[i]);
        }
        op=1; printf("%d",n);
        for(int i=2;i<=n;i++)
            sort(p+i,p+n+1,cmp),op++;
        for(int i=1;i<=n;i++) printf(" %d",p[i].id); putchar('\n');
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/lxy8584099/p/10419863.html