Pick-up sticks
| Time Limit: 3000MS | Memory Limit: 65536K | |
| Total Submissions: 9884 | Accepted: 3668 |
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.
Hint
Huge input,scanf is recommended.
Source
题意:判断线段是否相交;
利用跨立实验判断线段是否相交
#include <stdio.h>
struct point{
double x;
double y;
};
struct line{
point s;
point e;
}L[100005];
bool a[100005];
double min(double a,double b){
return a>b?b:a;
}
double max(double a,double b){
return a>b?a:b;
}
double multiply(point sp,point ep,point op){
return (sp.x-op.x)*(ep.y-op.y)-(ep.x-op.x)*(sp.y-op.y);
}
bool online(line l,point p){//是否在同一直线上
return ( (multiply(l.e,p,l.s)==0) && ((p.x-l.s.x)*(p.x-l.e.x)<=0) && ((p.y-l.s.y)*(p.y-l.e.y)<=0));
}
bool intersect(line u,line v)
{
return( (max(u.s.x,u.e.x)>=min(v.s.x,v.e.x))&&
(max(v.s.x,v.e.x)>=min(u.s.x,u.e.x))&&
(max(u.s.y,u.e.y)>=min(v.s.y,v.e.y))&&
(max(v.s.y,v.e.y)>=min(u.s.y,u.e.y))&&
(multiply(v.s,u.e,u.s)*multiply(u.e,v.e,u.s)>=0)&&
(multiply(u.s,v.e,v.s)*multiply(v.e,u.e,v.s)>=0));
}
int main(){
int n;
while(~scanf("%d",&n))
{
if(n==0)
return 0;
for(int i=0;i<n;i++){
scanf("%lf%lf%lf%lf",&L[i].s.x,&L[i].s.y,&L[i].e.x,&L[i].e.y);
a[i]=1;
}
for(int i=0;i<n;i++){
if(a[i]){
for(int j=i+1;j<n;j++){
if(intersect(L[i],L[j]))
{ a[i]=0;
break;
}
}
}
}
printf("Top sticks: ");
bool flag=1;
for(int i=0;i<n;i++){
if(a[i]){
if(flag){
printf("%d",i+1);
flag=0;
}
else
printf(", %d",i+1);
}
}
printf(".\n");
}
return 0;
}

本文介绍了一种通过跨立实验来判断线段是否相交的算法,并提供了一个完整的C语言实现示例。该算法首先定义了点和线段结构体,接着通过计算判断两线段是否存在交叉情况。此外,还提供了在线段上的判断逻辑。
489

被折叠的 条评论
为什么被折叠?



