tctony

Focus on linux,emacs,c/c++,python,algorithm...

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  17 随笔 :: 0 文章 :: 7 评论 :: 0 Trackbacks

You can Solve a Geometry Problem too

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 484    Accepted Submission(s): 219


Problem Description
Many geometry(几何)problems were designed in the ACM/ICPC. And now, I also prepare a geometry problem for this final exam. According to the experience of many ACMers, geometry problems are always much trouble, but this problem is very easy, after all we are now attending an exam, not a contest :)
Give you N (1<=N<=100) segments(线段), please output the number of all intersections(交点). You should count repeatedly if M (M>2) segments intersect at the same point.

Note:
You can assume that two segments would not intersect at more than one point.
 

Input
Input contains multiple test cases. Each test case contains a integer N (1=N<=100) in a line first, and then N lines follow. Each line describes one segment with four float values x1, y1, x2, y2 which are coordinates of the segment’s ending.
A test case starting with 0 terminates the input and this test case is not to be processed.
 

Output
For each case, print the number of intersections, and one line one case.
 

Sample Input
2
0.00 0.00 1.00 1.00
0.00 1.00 1.00 0.00
3
0.00 0.00 1.00 1.00
0.00 1.00 1.00 0.000
0.00 0.00 1.00 0.00
0
 

Sample Output
1
3


#include<iostream>
using namespace std;

double p[100][2],q[100][2];

double direction(double p[],double q[] ,double r[]){
    
return ((r[0]-p[0])*(q[1]-p[1])-(r[1]-p[1])*(q[0]-p[0]));
}


bool onsegment(double p[],double q[], double r[]){
    
if(((r[0]-p[0])*(r[0]-q[0])<=0)&&((r[1]-p[1])*(r[1]-q[1])<=0))
        
return true;
    
else return false;
}


bool judge(int i, int j){
    
double d1,d2,d3,d4;
    d1
=direction(p[i],q[i],p[j]);
    d2
=direction(p[i],q[i],q[j]);
    d3
=direction(p[j],q[j],p[i]);
    d4
=direction(p[j],q[j],q[i]);
    
if((d1*d2<0)&&(d3*d4<0))
        
return true;
    
else if(d1==0&& onsegment(p[i],q[i],p[j])==1)
        
return true;
    
else if(d2==0&& onsegment(p[i],q[i],q[j])==1)
        
return true;
    
else if(d3==0&& onsegment(p[j],q[j],p[i])==1)
        
return true;
    
else if(d4==0&& onsegment(p[j],q[j],q[i])==1)
        
return true;
    
else return false;
}


int main(){
    
int n,i,j,count;
    
while(scanf("%d",&n)){
        
if(n==0)    break;
        
for(i=0;i<n;++i){
            scanf(
"%lf %lf %lf %lf",&p[i][0],&p[i][1],&q[i][0],&q[i][1]);
        }

        
for(i=0,count=0;i<n;i++)
            
for(j=i+1;j<n;j++)
                
if(judge(i,j)==1)
                    
++count;
        printf(
"%d\n",count);
    }

    
return 0;
}


此题牵涉到线段是否相交的判定问题
posted on 2007-11-30 12:26 tctony 阅读(824) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   博问   Chat2DB   管理