LA 3027 并查集

比较基础的带权并查集,需要注意终止条件是'O'而不是'0'...

 1 #include <iostream>
 2 #include <cstring>
 3 #include <cstdio>
 4 #include <cmath>
 5 using namespace std;
 6 
 7 const int N = 20001;
 8 const int MOD = 1000;
 9 int f[N];
10 int d[N];
11 
12 void init( int n )
13 {
14     for ( int i = 1; i <= n; i++ )
15     {
16         f[i] = i;
17         d[i] = 0;
18     }
19 }
20 
21 void findf( int x )
22 {
23     if ( f[x] == x ) return ;
24     int tx = f[x];
25     findf(tx);    
26     d[x] += d[tx];
27     f[x] = f[tx];
28 }
29 
30 int main ()
31 {
32     int t;
33     scanf("%d", &t);
34     while ( t-- )
35     {
36         int n;
37         scanf("%d", &n);
38         init(n);
39         char op[2];
40         while ( scanf("%s", op) != EOF )
41         {
42             if ( op[0] == 'O' ) break;
43             int x, y;
44             if ( op[0] == 'E' )
45             {
46                 scanf("%d", &x);
47                 findf(x);
48                 printf("%d\n", d[x]);
49             }
50             else
51             {
52                 scanf("%d%d", &x, &y);
53                 f[x] = y;
54                 d[x] = ( ( int ) abs( x - y ) ) % MOD;
55             }
56         }
57     }
58     return 0;
59 }

 

posted @ 2015-08-24 09:06  hxy_has_been_used  阅读(150)  评论(0编辑  收藏  举报