You can Solve a Geometry Problem too 7.1.2

You can Solve a Geometry Problem too

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

Total Submission(s): 129    Accepted Submission(s): 91

 
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<cstdio>
#include<algorithm>
using namespace std;

const int MAXN = 100 + 10;
struct point {
	double x, y;
};
struct segment{
	point begin, end;
}s[MAXN];
double direction(point pi, point pj, point pk){
	//(pi - pk)*(pj - pk)
	return (pi.x - pk.x) * (pj.y - pk.y) - (pi.y - pk.y) * (pj.x - pk.x);
}
double on_segment(point pi, point pj, point pk){
	if(min(pi.x, pj.x) <= pk.x && max(pi.x, pj.x) >= pk.x && 
		min(pi.y, pj.y) <= pk.y && max(pi.y, pj.y) >= pk.y) return true;
		else return false;
}
bool intersect(segment a, segment b){
	double d1 = direction(b.begin, a.begin, a.end);
	double d2 = direction(b.end, a.begin, a.end);
	double d3 = direction(a.begin, b.begin, b.end);
	double d4 = direction(a.end, b.begin, b.end);
	if(((d1 > 0 && d2 < 0)||(d1 < 0) && d2 > 0) && ((d3 > 0 && d4 < 0)||(d3 < 0 && d4 > 0))) return true;
	else if(d1 == 0 && on_segment(a.begin, a.end, b.begin)) return true;
	else if(d2 == 0 && on_segment(a.begin, a.end, b.end)) return true;
	else if(d3 == 0 && on_segment(b.begin, b.end, a.begin)) return true;
	else if(d4 == 0 && on_segment(b.begin, b.end, a.end)) return true;
	else return false;
}
int main(){
	int n;
	double x1, y1, x2, y2;
	while(scanf("%d", &n) && n) {
		for(int i = 0; i < n; i++){
			scanf("%lf%lf%lf%lf", &x1, &y1, &x2, &y2);
			s[i].begin.x = x1;
			s[i].begin.y = y1;
			s[i].end.x = x2;
			s[i].end.y = y2;
		}
		int cnt = 0;
		for(int i = 0; i < n; i++){
			for(int j = i+1; j < n; j++){
				if(intersect(s[i], s[j])) cnt++;
			}
		}
		printf("%d\n", cnt);
	}
	return 1;
}

猜你喜欢

转载自blog.csdn.net/bruce_teng2011/article/details/38644861