作者:赖-哥_528 | 来源:互联网 | 2023-10-16 15:07
YoucanSolveaGeometryProblemtooProblemDescriptionManygeometry(几何)problemsweredesignedinth
You can Solve a Geometry Problem too
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
#include
#include
using namespace std;
const int maxn = 110;
struct ss
{
double x1, x2, y1, y2;
double k;
bool flag;
};
bool check(ss a, ss b)
{
//无斜率平行
if(a.flag == b.flag && a.flag == false) return false;
//有一直线无斜率
if(a.flag == false || b.flag == false)
{
//a无斜率
if(a.flag == false)
{
double y = b.k*a.x1 + b.y1 -b.k*b.x1;
if(y max(b.y1, b.y2)) return false;
else return true;
}
else//b无斜率
{
double y = a.k*b.x1 + a.y1 -a.k*a.x1;
if(y max(a.y1, a.y2)) return false;
else return true;
}
}
//有斜率平行
if(a.k == b.k) return false;
else//不平行
{
double x = (b.y1-b.k*b.x1-a.y1+a.k*a.x1)/(a.k-b.k);
if(x max(a.x1, a.x2) || x max(b.x1, b.x2)) return false;
else return true;
}
}
int N, ans;
int main()
{
while(scanf("%d", &N) != EOF && N)
{
ss f[maxn];
ans = 0;
for(int i = 0;i {
scanf("%lf %lf %lf %lf", &f[i].x1, &f[i].y1, &f[i].x2, &f[i].y2);
if(f[i].x1 > f[i].x2)
{
swap(f[i].x1, f[i].x2);
swap(f[i].y1, f[i].y2);
}
if(f[i].x1 == f[i].x2) f[i].flag = false;//无斜率
else
{
f[i].flag = true;//有斜率
f[i].k = (f[i].y2 - f[i].y1)/(f[i].x2 - f[i].x1);
}
}
for(int i = 1;i for(int j = 0;j {
if(check(f[i], f[j])) ans ++;
}
cout < }
return 0;
}