您的位置:首页 > 其它

poj1696 求一条螺旋线,类似凸包

2012-07-20 18:02 344 查看
题目链接:http://poj.org/problem?id=1696

题意:给定n个点,从最左下角那个点开始,求永不右转的最长路径。

思路:贪心,始终寻找最外面的点就行了,最后得到一条螺旋线,思路和凸包中的卷包裹法类似,O(n*n)的复杂度,仍是0ms,无需极坐标排序

#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
using namespace std;

const double eps = 1e-8;

bool visit[55];
int ans[55];

struct Point {
    double x, y;
} pset[55];

double getDis(Point a, Point b) {
    return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
}

double multi(Point p0, Point p1, Point p2) {
    return (p1.x-p0.x)*(p2.y-p0.y)-(p1.y-p0.y)*(p2.x-p0.x);
}

/*若有向线段ab在有向线段ac的
   顺时针方向,返回1;逆时针方向,返回-1;共线返回0
*/
int judge(Point a, Point b, Point c) {
    double res = multi(a, b, c);
    if (res > eps) return 1;
    else if (res < -eps) return -1;
    else return  0;
}

int main()
{
    int t, n, i, s, k, cnt, num;
    double tmp;

    scanf ("%d", &t);
    while (t--) {
        scanf ("%d", &n);
        s = 1;
        for (i = 1; i <= n; i++) {
            scanf ("%d%lf%lf", &num, &pset[i].x, &pset[i].y);
            tmp = pset[s].y - pset[i].y;
            if ((fabs(tmp) < eps && pset[i].x + eps < pset[s].x) || tmp > eps) s = i; //求最左下角的点,作为起点
        }
        memset(visit, false, sizeof (visit));
        visit[s] = true;
        cnt = 0;//记录已经确定顺序的点的点数
        ans[0] = s;//记录已确定的点
        while (cnt < n) {
            for (i = 1; i <= n; i++)//随意找一个未确定的点k
                if (!visit[i]) {
                    k = i; break;
                }
            //以sk作为基准向量,利用差积寻找相对s最靠右的一点
            for (i = k+1; i <= n; i++)
                if (!visit[i]) {
                    tmp = judge(pset[s], pset[i], pset[k]);
                    if ((tmp > 0) || (tmp == 0 && getDis(pset[s], pset[k]) > getDis(pset[s], pset[i]) + eps))
                         k = i;
                }
            ans[++cnt] = k;//记录新确定的点
            visit[k] = true;
            s = k;//以新确定的点作为s点
        }
        printf ("%d", n);
        for (i = 0; i < n; i++) printf (" %d", ans[i]);
        printf ("\n");
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: