1. 程式人生 > >2653 Pick-up sticks

2653 Pick-up sticks

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.

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.

 題目大意:n個棒子仍在平面內,輸出最上面的棒子

解題思路:直接使用線段相交的模板即可;從第一個線段開始,遍歷其後面的所有線段,如果都不相交,則輸出

AC程式碼:

#include<iostream>
#include<algorithm>
using namespace std;
struct point
{
    double x,y;
}p[100010],q[100010];
bool inter(point a,point b,point c,point d)
{
    if(min(a.x,b.x)>max(c.x,d.x)||min(a.y,b.y)>max(c.y,d.y)||min(c.x,d.x)>max(a.x,b.x)||min(c.y,d.y)>max(a.y,b.y))
        return 0;//快速排斥實驗 
    double h,i,j,k;
    h=(b.x-a.x)*(c.y-a.y)-(b.y-a.y)*(c.x-a.x);
    i=(b.x-a.x)*(d.y-a.y)-(b.y-a.y)*(d.x-a.x);
    j=(d.x-c.x)*(a.y-c.y)-(d.y-c.y)*(a.x-c.x);
    k=(d.x-c.x)*(b.y-c.y)-(d.y-c.y)*(b.x-c.x);
    return h*i<=0&&j*k<=0;//跨立實驗 
}
 
int main()
{
    int n;
    while(scanf("%d",&n),n)
    {
        int i,j;
        for(i=1;i<=n;i++)
            scanf("%lf%lf%lf%lf",&p[i].x,&p[i].y,&q[i].x,&q[i].y);
        printf("Top sticks: ");
        for(i=1;i<n;i++)
        {
            for(j=i+1;j<=n;j++)
            {
                if(inter(p[i],q[i],p[j],q[j]))
                {
                    break;
                }
            }
            if(j==n+1)
            	printf("%d, ",i);
        }
        printf("%d.\n",n);//最後一個一定是最上面的那個,輸出 
    }
    return 0;
}