Pick-up sticks
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 2577 Accepted Submission(s): 937
Problem 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.
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.
Source
分析:
判断线段相交,大白书第四章
代码:
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
const int maxn = 1e5 + 10;
struct Point //点
{
double x, y;
Point(double x = 0, double y = 0) : x(x), y(y) {} //构造函数,方便代码编写
};
struct Segment //线段
{
Point p1, p2;
} S[maxn];
int vis[maxn];
typedef Point Vector; //Vector 是 Point 的别名
//点-点=向量
Vector operator - (Point A, Point B)
{
return Vector(A.x - B.x, A.y - B.y);
}
const double eps = 1e-10;
//三态函数,减少精度问题
int dcmp(double x)
{
if (fabs(x) < eps) return 0;
else return x < 0 ? -1 : 1;
}
//两向量的叉积
double Cross(Vector A, Vector B)
{
return A.x * B.y - A.y * B.x;
}
//判定线段是否“规范相交”
bool SegmentProperIntersection(Point a1, Point a2, Point b1, Point b2)
{
double c1 = Cross(a2 - a1, b1 - a1), c2 = Cross(a2 - a1, b2 - a1),
c3 = Cross(b2 - b1, a1 - b1), c4 = Cross(b2 - b1, a2 - b1);
return dcmp(c1) * dcmp(c2) < 0 && dcmp(c3) * dcmp(c4) < 0;
}
int main()
{
int n;
while (~scanf("%d", &n) && n != 0)
{
memset(vis, 0, sizeof(vis));
for (int i = 1; i <= n; i++)
scanf("%lf%lf%lf%lf", &S[i].p1.x, &S[i].p1.y, &S[i].p2.x, &S[i].p2.y);
for (int i = 1; i < n; i++) //判断第i个线段是否被后面的覆盖
{
for (int j = i + 1; j <= n; j++)
{
if (SegmentProperIntersection(S[i].p1, S[i].p2, S[j].p1, S[j].p2))
{
vis[i] = 1;
break;
}
}
}
printf("Top sticks: ");
int ok = 0;
for (int i = 1; i <= n; i++)
{
if (!vis[i])
{
if (ok) printf(", ");
ok = 1;
printf("%d", i);
}
}
printf(".\n");
}
return 0;
}