kuangbin带我飞QAQ 并查集

  1. POJ 2236

  给出N个点,一开始图是空白的,两个操作,一个是增加一个点(给出坐标),一个是查询两个点间是否相通,当两点间的距离小于D或者两点通过其他点间接相连时说这两个点相通。并查集维护,每次增加一个点加入到vector中并于之前的点比较,距离小于D则合并到一个集合即可。

 1 #include <iostream>
 2 #include <string.h>
 3 #include <cstdio>
 4 #include <vector>
 5 #include <string>
 6 #include <algorithm>
 7 #include <math.h>
 8 #include <time.h>
 9 
10 #define SIGMA_SIZE 26
11 #define lson rt<<1
12 #define rson rt<<1|1
13 #pragma warning ( disable : 4996 )
14 
15 using namespace std;
16 typedef long long LL;
17 inline LL LMax(LL a,LL b)      { return a>b?a:b; }
18 inline LL LMin(LL a,LL b)      { return a>b?b:a; }
19 inline int Max(int a,int b)    { return a>b?a:b; }
20 inline int Min(int a,int b)       { return a>b?b:a; }
21 inline int gcd( int a, int b ) { return b==0?a:gcd(b,a%b); }
22 inline int lcm( int a, int b ) { return a/gcd(a,b)*b; }  //a*b = gcd*lcm
23 const LL INF = 0x3f3f3f3f3f3f3f3f;
24 const LL mod  = 1000000007;
25 const double eps = 1e-8;
26 const int inf  = 0x3f3f3f3f;
27 const int maxk = 1005;
28 const int maxn = 1030;
29 
30 int N, D;
31 vector<int> alive;
32 bool vis[maxk];
33 int root[maxk];
34 int xi[maxk], yi[maxk];
35 
36 
37 int find( int x )
38 { return x==root[x] ? x : root[x]=find(root[x]); }
39 
40 void join( int x, int y )
41 {
42     x = find(x); y = find(y);
43     if ( x == y )
44         return;
45     root[x] = y;
46 }
47 
48 int getDist( int i, int j )
49 { return (xi[i]-xi[j])*(xi[i]-xi[j]) + (yi[i]-yi[j])*(yi[i]-yi[j]) ; }
50 
51 void init()
52 {
53     alive.clear();
54     memset(vis, 0, sizeof(vis) );
55 
56     for ( int i = 0; i < maxk; i++ )
57         root[i] = i;
58 
59     for ( int i = 1; i <= N; i++ )
60         scanf( "%d %d", &xi[i], &yi[i] );
61 }
62 
63 int main()
64 {
65     freopen("F:\\cpp\\test.txt", "r", stdin );
66     scanf("%d %d", &N, &D);
67     init();
68 
69     int x, y;
70     char str[5];
71     while ( ~scanf("%s", str) )
72     {
73         if ( str[0] == 'O' )
74         {
75             scanf("%d", &x);
76             vis[x] = true;
77             alive.push_back(x);
78 
79             for ( int i = 0; i < alive.size()-1; i++ )
80                 if ( getDist(alive[i], x) <= D*D )
81                     join(alive[i], x);
82         }
83         else
84         {
85             scanf("%d %d", &x, &y);
86             if ( (!vis[x]) || (!vis[y]) )
87                 printf("FAIL\n");
88             else
89             {
90                 x = find(x); y = find(y);
91                 if ( x == y )
92                     printf("SUCCESS\n");
93                 else
94                     printf("FAIL\n");
95             }
96         }
97     }
98 }
View Code

猜你喜欢

转载自www.cnblogs.com/chaoswr/p/9125757.html