HDU 1086 You can Solve a Geometry Problem too

http://acm.hdu.edu.cn/showproblem.php?pid=1086

判断两线段是否相交,用向量搞了

View Code
#include <iostream>

using namespace std ;

struct point{

    double x,y ;

} ;

typedef struct L{

    point p1,p2 ;

}L ;

L kk[110] ;

double direction(point p1,point p2,point p)

{

    return (p.x-p1.x)*(p1.y-p2.y)-(p1.x-p2.x)*(p.y-p1.y) ;

}

bool online(point p1,point p2,point p)

{

    return (p.x<=max(p1.x,p2.x) && p.x>=min(p1.x,p2.x) && p.y<=max(p1.y,p2.y) && p.y>=min(p1.y,p2.y)) ;

}

bool intersect(point p1,point p2,point p3,point p4)

{

    double d1=direction(p3,p4,p1) ;

    double d2=direction(p3,p4,p2) ;

    double d3=direction(p1,p2,p3) ;

    double d4=direction(p1,p2,p4) ;

    if(d1*d2<0 && d3*d4<0)

        return true ;

    if(d1==0 && online(p3,p4,p1)) 

        return true ;

    if(d2==0 && online(p3,p4,p2))

        return true ;

    if(d3==0 && online(p1,p2,p3))

        return true ;

    if(d4==0 && online(p1,p2,p4))

        return true ;

    return false ;

}

int main()

{

    int n ;

    while(scanf("%d",&n),n)

    {

        int ans=0 ;

        for(int i=0;i<n;i++)

            scanf("%lf%lf%lf%lf",&kk[i].p1.x,&kk[i].p1.y,&kk[i].p2.x,&kk[i].p2.y) ;

        for(int i=0;i<n;i++)

            for(int j=i+1;j<n;j++)

                if(intersect(kk[i].p1,kk[i].p2,kk[j].p1,kk[j].p2))

                    ans++ ;

        printf("%d\n",ans) ;

    }

    return 0 ;

} 

 

你可能感兴趣的:(HDU)