首页 > 代码库 > Pick-up sticks(计算几何_线段相交)
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.
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条线段,按照顺序将每条线段在坐标轴上表示出来,问那些线段没有相交,依次输出他们。思路:用线段相交的方法依次遍历出相交的线段,剩下的没有相交的线段就是题目所求。注意输出格式,被坑了一次;#include <stdio.h> #include <string.h> #include <stdlib.h> #include <iostream> #include <algorithm> using namespace std; struct point { double x,y; }; struct line { point p1,p2; } a[100010]; double chacheng (struct point p1,struct point p2,point p3) { return (p1.x-p3.x)*(p2.y-p3.y)-(p1.y-p3.y)*(p2.x-p3.x); } int judge(struct line l1,struct line l2) { if( min(l2.p1.x,l2.p2.x)<=max(l1.p1.x,l1.p2.x)&&min(l2.p1.y,l2.p2.y)<=max(l1.p1.y,l1.p2.y)&&min(l1.p1.x,l1.p2.x)<=max(l2.p1.x,l2.p2.x) &&min(l1.p1.y,l1.p2.y)<=max(l2.p1.y,l2.p2.y) &&chacheng(l1.p1,l2.p2,l2.p1)*chacheng(l1.p2,l2.p2,l2.p1)<=0 &&chacheng(l2.p1,l1.p2,l1.p1)*chacheng(l2.p2,l1.p2,l1.p1)<=0 ) return 1; else return 0; } int main() { int n,i,j; int flag[100010]; while(~scanf("%d",&n)) { if(n==0) break; for(i=0; i<n; i++) scanf("%lf %lf %lf %lf",&a[i].p1.x,&a[i].p1.y,&a[i].p2.x,&a[i].p2.y); memset(flag,0,sizeof(flag)); for(i=0; i<n-1; i++) for(j=i+1; j<n; j++) if(judge(a[i],a[j])) { flag[i]=1; break; } printf("Top sticks: "); for(i=0; i<n; i++) if(flag[i]==0) { if(i==n-1) printf("%d.\n",i+1); else printf("%d, ",i+1); } } return 0; }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。