您的位置:首页 > 其它

hdu1086+You can Solve a Geometry Problem too(计算几何,计算线段交点个数)

2014-11-10 12:28 197 查看

You can Solve a Geometry Problem too

[b]Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)

Total Submission(s): 7732 Accepted Submission(s): 3775

[/b]

[align=left]Problem Description[/align]
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.

[align=left]Input[/align]
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.

[align=left]Output[/align]
For each case, print the number of intersections, and one line one case.

[align=left]Sample Input[/align]

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


[align=left]Sample Output[/align]

1
3


题意很简单就是让你计算多条直线一共产生多少交点,运用了计算几何的排斥试验和跨立试验,排斥试验是两条直线相交的必要条件,跨立试验是计算两条直线向量的叉积,叉积为负才有交点。假设点为(x1,y1),(x2,y2)叉积为x1*y2 - y1*x2,点积为x1*x2 + y1*y2。下面贴代码:
#include<iostream>
#include<cstring>
#include<cmath>
#include<cstdio>
#include<algorithm>
int m;
const int maxn = 105;
using namespace std;
struct Point//表示坐标
{
double x,y;
};
struct Seg//s,e分别表示第一条线段和第二条线段
{
Point s,e;
}p[maxn];
double cross(Point p1,Point p2,Point p3)    //叉积
{
double d1 = p2.x - p1.x;//用了int型,WA了几发
double d2 = p2.y - p1.y;
double d3 = p3.x - p2.x;
double d4 = p3.y - p2.y;
return d1 * d4 - d3 * d2;
}
bool cal(Seg a,Seg b)
{
if (max(a.s.x,a.e.x) >= min(b.s.x,b.e.x) &&  //排斥试验
max(b.s.x,b.e.x)>=min(a.s.x,a.e.x) &&
max(a.s.y,a.e.y) >= min(b.s.y,b.e.y) &&
max(b.s.y,b.e.y)>=min(a.s.y,a.e.y) &&
cross(b.s,a.e,a.s) * cross(b.e,a.e,a.s)<=0 &&    //跨立试验
cross(a.s,b.e,b.s) * cross(a.e,b.e,b.s)<=0)
return true;
else
return false;
}
int res()//两两判断,时间复杂度为(O(n^2))
{
int i,j,cnt = 0;
for(i=1;i<=m;i++)
{
for(j=i+1;j<=m;j++)
{
if(cal(p[i],p[j]))
cnt++;
}
}
return cnt;
}
int main()
{
//freopen("1.in","r",stdin);
while(cin>>m && m)
{
int result;
for(int i=1;i<=m;i++)
{
cin>>p[i].e.x>>p[i].e.y>>p[i].s.x>>p[i].s.y;
}
result = res();
cout<<result<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: