您的位置:首页 > 其它

POJ2653 Pick-up sticks 判断线段相交

2011-08-10 21:31 183 查看
Problem Address:http://poj.org/problem?id=2653

【前言】

试试判断线段相交的题。

几何的东西一直都是不太敢碰的。

discuss里一片tle。

后来写写写,然后就一次AC了。

【思路】

如何判断线段相交?

分别用两条线段的两个端点与另一条线段的两个端点做叉乘并相乘,如果两个结果都小于零,则两线段相交。

从下往上枚举每一条边,如果当前边与之前的边相交,则前面的边不可能成为top stick。

n=100000。一般情况下n2复杂度的算法是会超时的。

不过由于这道题已有说明top sticks最多不超过m=1000。

所以nm的复杂度还是可以接受的。

我用两个数组模拟了链表,实现了O(nm)。

顺便链接一个地址,里面有讲解各种判断,虽然我不是从里面抄袭的。

http://wenku.baidu.com/view/ae559264783e0912a2162a79.html

【代码】

#include <iostream>
using namespace std;

const int maxn = 100000;

struct point
{
double x;
double y;
};

struct seg
{
point begin;
point end;
}s[maxn+5];

int ct;
int next[maxn+5];
int pre[maxn+5];

inline double cross(point a, point b, point t)//计算叉积
{
return (a.x-t.x)*(b.y-t.y) - (b.x-t.x)*(a.y-t.y);
}

inline bool segcross(seg a, seg b)//判断相交
{
double d1 = cross(a.begin, a.end, b.begin);
double d2 = cross(a.begin, a.end, b.end);
double d3 = cross(b.begin, b.end, a.begin);
double d4 = cross(b.begin, b.end, a.end);
if (d1*d2<0 && d3*d4<0) return true;
else return false;
}

int main()
{
int n;
int i, j;
while(scanf("%d", &n)!=EOF)
{
if (n==0) break;
ct = 0;
for (i=1; i<=n; i++)
{
scanf("%lf %lf %lf %lf", &s[i].begin.x, &s[i].begin.y, &s[i].end.x, &s[i].end.y);
next[i] = i+1;
pre[i] = i-1;
}
next[0] = 1;
next
= -1;
ct = n;
for (i=1; i<=n; i++)
{
for (j=next[0]; j<i; j=next[j])//与前面的边比较,注意j起始点为next[0],避免删掉第一个点的情况。存储位置从0算起,next[0]初始值为1。
{
if (segcross(s[i], s[j]))//如果相交则去掉该索引
{
ct--;
next[pre[j]] = next[j];
pre[next[j]] = pre[j];
}
}
}
printf("Top sticks: ");
for (i=0,j=next[0]; i<ct; i++,j=next[j])
{
if (i==0) printf("%d", j);
else printf(", %d", j);
}
printf(".\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: