原题:
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
0Sample Output
0
3
解题思路:
非常基础的计算几何!!
代码:
#include <stdio.h>
#include <algorithm>
using namespace std;
struct Point
{
float x, y;
};
struct Line
{
Point p1, p2;
} line[101];
float Direction(Point i,Point j,Point k)//判断线段ij和ik的方向
{
return (k.x - i.x)*(j.y - i.y) - (k.y - i.y)*(j.x - i.x);//(Pk-Pi)×(Pj-Pi) > 0则ik在ij的顺时针方向
}
bool OnSegment(Point i, Point j, Point k) {//判断k点是否在ij线段上
if(k.x >= min(i.x, j.x) && k.x <= max(i.x, j.x) && k.y >= min(i.y, j.y) && k.y <= max(i.y, j.y))
return true;
return false;
}
bool SegmentsIntersect(Line l1,Line l2)//判断线段是否相交
{
float d1, d2, d3, d4;
d1 = Direction(l1.p1, l1.p2, l2.p1);
d2 = Direction(l1.p1, l1.p2, l2.p2);
d3 = Direction(l2.p1, l2.p2, l1.p1);
d4 = Direction(l2.p1, l2.p2, l1.p2);
if (d1*d2 < 0 && d3*d4 < 0)
return true;
if (d1 == 0 && OnSegment(l1.p1, l1.p2, l2.p1))return true;
if (d2 == 0 && OnSegment(l1.p1, l1.p2, l2.p2))return true;
if (d3 == 0 && OnSegment(l2.p1, l2.p2, l1.p1))return true;
if (d4 == 0 && OnSegment(l2.p1, l2.p2, l1.p2))return true;
return false;
}
int main()
{
int N, i, j;
int count;
while (scanf("%d",&N)!=EOF&&N!=0)
{
count = 0;
for (i = 1; i <= N; i++)
scanf("%f%f%f%f", &line[i].p1.x, &line[i].p1.y, &line[i].p2.x, &line[i].p2.y);
for (i = 1; i <= N; i++)
for (j = i + 1; j <= N; j++)
{
if (SegmentsIntersect(line[i], line[j]))count++;
}
printf("%d\n", count);
}
}