您的位置:首页 > 其它

hdu 1086 You can Solve a Geometry Problem too(线段相交点的个数)

2015-09-16 23:00 381 查看
题目地址

题目大意:给定n条线段,求共有多少个交点(交点重复时算多个)

解题思路:用差乘判断线段是否相交(一条线段的两个点分别与另外一条线段的差乘相乘<=0,则相交)

#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <queue>
#include <string>
#include <map>
#include <stack>
#include <list>
#include <set>

using namespace std;

const int maxn = 100+10;
const double eps = 1e-10;

struct Point
{
double x;
double y;
Point(double x = 0, double y = 0) : x(x),y(y){}
}point1[maxn],point2[maxn];

typedef Point Vector;

Vector operator - (Point A, Point B)
{
return Vector(A.x-B.x, A.y-B.y);
}

double Cross(Vector A,Vector B)
{
return A.x * B.y - A.y * B.x;
}

int dcmp(double x)
{
if(fabs(x) < eps)
return 0;
else
return x > 0 ? 1 : -1;
}

bool SegmentProperIntersection(Point A,Point B,Point C,Point D)
{
double c1 = Cross(B-A,C-A);
double c2 = Cross(B-A,D-A);
double c3 = Cross(D-C,A-C);
double c4 = Cross(D-C,B-C);
return dcmp(c1) * dcmp(c2) <= 0 && dcmp(c3) * dcmp(c4) <= 0;
}

int main()
{
int n;
int tot;
while(scanf("%d",&n) != EOF && n)
{
for(int i = 0; i < n; i++)
scanf("%lf%lf%lf%lf",&point1[i].x,&point1[i].y,&point2[i].x,&point2[i].y);
tot = 0;
for(int i = 0; i < n ; i++)
{
for(int j = i+1; j < n; j++)
{
if(SegmentProperIntersection(point1[i],point2[i],point1[j],point2[j]))
tot++;
}
}
printf("%d\n",tot);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: