You can Solve a Geometry Problem too
题目:http://acm.hdu.edu.cn/showproblem.php?pid=1086
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;
const double EPS = 1e-10;
struct point
{
double x,y;
};
struct line
{
point a,b;
}l[100001];
double Max(double a,double b) {return a>b?a:b;}
double Min(double a,double b) {return a>b?b:a;}
// 判断两线段是否相交(非规范相交)
bool inter(line l1,line l2)
{
point p1,p2,p3,p4;
p1=l1.a;p2=l1.b;
p3=l2.a;p4=l2.b;
if( Min(p1.x,p2.x)>Max(p3.x,p4.x) ||
Min(p1.y,p2.y)>Max(p3.y,p4.y) ||
Min(p3.x,p4.x)>Max(p1.x,p2.x) ||
Min(p3.y,p4.y)>Max(p1.y,p2.y) )
return 0;
double k1,k2,k3,k4;
k1 = (p2.x-p1.x)*(p3.y-p1.y) - (p2.y-p1.y)*(p3.x-p1.x);
k2 = (p2.x-p1.x)*(p4.y-p1.y) - (p2.y-p1.y)*(p4.x-p1.x);
k3 = (p4.x-p3.x)*(p1.y-p3.y) - (p4.y-p3.y)*(p1.x-p3.x);
k4 = (p4.x-p3.x)*(p2.y-p3.y) - (p4.y-p3.y)*(p2.x-p3.x);
return (k1*k2<=EPS && k3*k4<=EPS);
}
int main()
{
int n,i,j,sum;
while( cin>>n && n)
{
for(i=0;i<n;++i)
cin>>l[i].a.x>>l[i].a.y>>l[i].b.x>>l[i].b.y;
sum=0;
for(i=0;i<n;++i)
for(j=i+1;j<n;++j)
if( inter(l[i],l[j]) )
++sum;
cout<<sum<<endl;
}
return 0;
}

本文介绍了一个关于计算平面内线段交点数量的几何问题,通过给出的C++代码实现,采用非规范相交算法来解决该问题。输入包含多个测试案例,每个案例给出一系列线段坐标,输出所有线段间的交点总数。
3822

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



