【POJ 2653】Pick-up sticks

【题目】

传送门

Description

Stan has n sticks of various length. He throws them one at a time on the floor in a random way. After finishing throwing, Stan tries to find the top sticks, that is these sticks such that there is no stick on top of them. Stan has noticed that the last thrown stick is always on top but he wants to know all the sticks that are on top. Stan sticks are very, very thin such that their thickness can be neglected.

Input

Input consists of a number of cases. The data for each case start with 1 <= n <= 100000, the number of sticks for this case. The following n lines contain four numbers each, these numbers are the planar coordinates of the endpoints of one stick. The sticks are listed in the order in which Stan has thrown them. You may assume that there are no more than 1000 top sticks. The input is ended by the case with n=0. This case should not be processed.

Output

For each input case, print one line of output listing the top sticks in the format given in the sample. The top sticks should be listed in order in which they were thrown.

The picture to the right below illustrates the first case from input.
【POJ 2653】Pick-up sticks
Sample Input

5
1 1 4 2
2 3 3 1
1 -2.0 8 4
1 4 8 2
3 3 6 -2.0
3
0 0 1 1
1 0 2 1
2 0 3 1
0

Sample Output

Top sticks: 2, 4, 5.
Top sticks: 1, 2, 3.

Hint

Huge input,scanf is recommended.


【分析】

题目大意:按顺序扔出 nn 条线段,找出顶部的线段,按输入顺序输出它们的编号。

不难发现,对于一条先扔的线段 xx 和后扔的线段 yy,如果 xxyy 有交点,那 xx 就不可能在顶部。

那么对于每条线段,枚举比它后扔的所有线段,判断有无交点即可。

判断有无交点也很简单,对于 x,yx,y 两条线段,判断 xx 的两端点是否在 yy 的两侧,yy 的两端点是否在 xx 的两侧就可以了。

最后吐槽一下这道题。
题目中的 n105n\le10^5 让我一脸懵逼,不知道怎么去写,想了半天正解也没想出来。
然后去搜题解,发现全都是暴力。。。
自己写了写暴力,过了。。。

不过话说这道题我只找到了暴力啊,说不定这道题就是道神题但数据水呢

所以如果有好想法的就请告诉我,谢谢啦。


【代码】

#include<cstdio>
#include<cstring>
#include<algorithm>
#define N 100005
#define eps 1e-8
using namespace std;
int ans[N];
struct point
{
	double x,y;
	point(){}
	point(double x,double y):x(x),y(y){}
	point operator+(const point &a){return point(x+a.x,y+a.y);}
	point operator-(const point &a){return point(x-a.x,y-a.y);}
	friend double dot(const point &a,const point &b){return a.x*b.x+a.y*b.y;}
	friend double cross(const point &a,const point &b){return a.x*b.y-b.x*a.y;}
};
struct line
{
	point s,t;
	line(){}
	line(point s,point t):s(s),t(t){}
}l[N];
bool inter(line p,line q)
{
	double temp1=cross(q.s-p.s,q.t-p.s)*cross(q.s-p.t,q.t-p.t);
	double temp2=cross(p.s-q.s,p.t-q.s)*cross(p.s-q.t,p.t-q.t);
	return temp1<eps&&temp2<eps;
}
int main()
{
	int n,i,j;
	double x1,y1,x2,y2;
	while(~scanf("%d",&n))
	{
		int tot=0;
		if(!n)  break;
		printf("Top sticks:");
		for(i=1;i<=n;++i)
		{
			scanf("%lf%lf%lf%lf",&x1,&y1,&x2,&y2);
			l[i]=line(point(x1,y1),point(x2,y2));
		}
		for(i=1;i<=n;++i)
		{
			for(j=i+1;j<=n;++j)
			  if(inter(l[i],l[j]))
			    break;
			if(j>n)  ans[++tot]=i;
		}
		for(i=1;i<tot;++i)  printf(" %d,",ans[i]);
		printf(" %d.\n",n);
	}
	return 0;
}