HDU 1086 You can Solve a Geometry Problem too

本文解析了一道ACM竞赛中的几何题目,该题要求计算给定线段间的交点总数,并考虑了多条线段在同一交点相交的情况。通过判断线段两端点是否分别位于另一线段两端的方法来解决此问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
 
题解:
直接判断线段两端点是否分别在另一线段两端
 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <algorithm>
 5 #include <cmath>
 6 using namespace std;
 7 const int N=205;const double eps=1e-4;
 8 struct P{
 9     double x,y;
10     P(){};
11     P(double _x,double _y){x=_x;y=_y;}
12     P operator- (P a)const{
13         return P(x-a.x,y-a.y);
14     }
15     double operator^ (const P a)const{
16         return x*a.y-a.x*y;
17     }
18     P operator* (double k)const{
19         return P(k*x,k*y);
20     }
21     P operator+ (const P a)const{
22         return P(x+a.x,y+a.y);
23     }
24 };
25 int n;
26 struct Line{
27     P px,py;
28 }a[N];
29 double dot(P A,P B,P C){
30     return ((A-C)^(B-C));
31 }
32 bool check(int i,int j){
33     P pi1=a[i].px,pi2=a[i].py,pj1=a[j].px,pj2=a[j].py;
34     double t1,t2;
35     t1=dot(pi1,pi2,pj1)*dot(pi1,pi2,pj2);
36    t2=dot(pj1,pj2,pi1)*dot(pj1,pj2,pi2);
37     if(t1<eps && t2<eps)return true;
38     return false;
39 }
40 void work(){
41     for(int i=1;i<=n;i++){
42         scanf("%lf%lf%lf%lf",&a[i].px.x,&a[i].px.y,&a[i].py.x,&a[i].py.y);
43     }
44     int ans=0;
45     for(int i=1;i<=n;i++){
46         for(int j=i+1;j<=n;j++){
47             if(check(i,j))ans++;
48         }
49     }
50     printf("%d\n",ans);
51 }
52 int main()
53 {
54     while(scanf("%d",&n)){
55         if(!n)break;
56         work();
57     }
58     return 0;
59 }

 

转载于:https://www.cnblogs.com/Yuzao/p/7257975.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值