题目:http://acm.hdu.edu.cn/showproblem.php?pid=1558

判断两条线段是否相交,如果相交就是在一个集合内,问第i条线段所在集合的元素个数。

判断线段相交+并查集

代码:

View Code
  1 #include<stdio.h>
2 #define maxn 1001
3 int dnum[maxn],father[maxn];
4
5 struct node
6 {
7 double sx,sy,ex,ey;
8 }line[maxn];
9
10 double direction(double x1,double y1,double x2,double y2,double x,double y)
11 {
12 return (x1-x)*(y2-y)-(x2-x)*(y1-y);
13 }
14
15 bool on_segment(double x1,double y1,double x2,double y2,double x,double y)
16 {
17 int min,max;
18 if(x1<x2)
19 {
20 min=x1;
21 max=x2;
22 }
23 else
24 {
25 min=x2;
26 max=x1;
27 }
28 if(x>=min&&x<=max)
29 return 1;
30 return 0;
31 }
32
33 bool intersect_segment(int i,int j)
34 {
35 double d1=direction(line[i].sx,line[i].sy,line[i].ex,line[i].ey,line[j].sx,line[j].sy);
36 double d2=direction(line[i].sx,line[i].sy,line[i].ex,line[i].ey,line[j].ex,line[j].ey);
37 double d3=direction(line[j].sx,line[j].sy,line[j].ex,line[j].ey,line[i].sx,line[i].sy);
38 double d4=direction(line[j].sx,line[j].sy,line[j].ex,line[j].ey,line[i].ex,line[i].ey);
39 if(d1*d2<0&&d3*d4<0)
40 return 1;
41 if(d1==0&&on_segment(line[i].sx,line[i].sy,line[i].ex,line[i].ey,line[j].sx,line[j].sy))
42 return 1;
43 if(d2==0&&on_segment(line[i].sx,line[i].sy,line[i].ex,line[i].ey,line[j].ex,line[j].ey))
44 return 1;
45 if(d3==0&&on_segment(line[j].sx,line[j].sy,line[j].ex,line[j].ey,line[i].sx,line[i].sy))
46 return 1;
47 if(d4==0&&on_segment(line[j].sx,line[j].sy,line[j].ex,line[j].ey,line[i].ex,line[i].ey))
48 return 1;
49 return 0;
50 }
51
52 int find(int x)
53 {
54 int j,i=x;
55 while(x!=father[x])
56 x=father[x];
57 while(i!=x)
58 {
59 j=father[i];
60 father[i]=x;
61 i=j;
62 }
63 return x;
64 }
65
66 void add_to_set(int n)
67 {
68 int i,fx,fy;
69 for(i=1;i<n;i++)
70 {
71 if(intersect_segment(i,n))
72 {
73 fx=find(i);
74 fy=find(n);
75 if(fx!=fy)
76 {
77 father[fx]=fy;
78 dnum[fy]+=dnum[fx];
79 }
80 }
81 }
82 }
83
84 int main()
85 {
86 int t,i,n,fx,num,m;
87 char ch;
88 while(scanf("%d",&t)!=EOF)
89 {
90 while(t--)
91 {
92 n=1;
93 for(i=0;i<1001;i++)
94 {
95 father[i]=i;
96 dnum[i]=1;
97 }
98 scanf("%d",&m);
99 while(m--)
100 {
101 getchar();
102 scanf("%c",&ch);
103 if(ch=='P')
104 {
105 scanf("%lf%lf%lf%lf",&line[n].sx,&line[n].sy,&line[n].ex,&line[n].ey);
106 if(n>0)
107 add_to_set(n);
108 n++;
109 }
110 else
111 {
112 scanf("%d",&num);
113 fx=find(num);
114 printf("%d\n",dnum[fx]);
115 }
116 }
117 if(t>0)
118 printf("\n");
119 }
120 }
121 return 0;
122 }

  

 posted on 2011-07-28 15:45  渲染独白  阅读(327)  评论(0编辑  收藏  举报