题目描述:http://poj.org/problem?id=2653
解题思路:
无非是判断线段相交。但是由于n的范围有100000,读入之后O(n^2)枚举肯定不行。注意题目有一句:You may assume that there are no more than 1000 top sticks.
所以读入的时候在线维护一个top sticks的链表就好了。
但是.. 我用O(n^2)的方法还是过了,而且比静态链表快..
#include <stdio.h>
#define max(a,b) a>b?a:b
#define min(a,b) a>b?b:a
struct point
{
double x;
double y;
} pa[100007],pb[100007];
long n,i,j;
double direction(struct point a,struct point b,struct point c)
{
double x1=b.x-a.x,y1=b.y-a.y,
x2=c.x-b.x,y2=c.y-b.y;
return x1*y2-x2*y1;
}
int on_segment(struct point a,struct point b,struct point c)
{
if((min(a.x,b.x)<=c.x && c.x<=max(a.x,b.x)) && (min(a.y,b.y)<=c.y && c.y<=max(a.y,b.y))) return 1;
return 0;
}
int intersection(struct point p1,struct point p2,struct point p3,struct point p4)
{
double d1=direction(p3,p4,p1),
d2=direction(p3,p4,p2),
d3=direction(p1,p2,p3),
d4=direction(p1,p2,p4);
if(((d1>0 && d2<0) || (d1<0 && d2>0)) && ((d3>0 && d4<0)||(d3<0 && d4>0))) return 1;
if(!d1 && on_segment(p3,p4,p1)) return 1;
if(!d2 && on_segment(p3,p4,p2)) return 1;
if(!d3 && on_segment(p1,p2,p3)) return 1;
if(!d4 && on_segment(p1,p2,p4)) return 1;
return 0;
}
int main()
{
scanf("%ld",&n);
while(n)
{
printf("Top sticks:");
for(i=1;i<=n;i++) scanf("%lf%lf%lf%lf",&pa[i].x,&pa[i].y,&pb[i].x,&pb[i].y);
for(i=1;i<n;i++)
{
int k=1;
for(j=i+1;j<=n;j++)
if(intersection(pa[i],pb[i],pa[j],pb[j]))
{
k=0;
break;
}
if(k)printf(" %ld,",i);
}
printf(" %ld.\n",n);
scanf("%ld",&n);
}
return 0;
}