xpycc

posts(1) comments(0) trackbacks(0)
  • C++博客
  • 联系
  • RSS 2.0 Feed 聚合
  • 管理

常用链接

  • 我的随笔
  • 我的评论
  • 我参与的随笔

留言簿

  • 给我留言
  • 查看公开留言
  • 查看私人留言

随笔档案

  • 2010年9月 (1)

搜索

  •  

最新评论

View Post

hdu 3635

N 久没写并查集了,昨天练习比赛突然有,就当热身吧。

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <algorithm>
 4 using namespace std;
 5 #define MAXN 10000
 6 
 7 int father[MAXN + 1], trans[MAXN + 1], sum[MAXN + 1];
 8 
 9 void init_set(int n) {
10     for (int i = 1; i <= n; ++i) {
11         father[i] = i;
12         trans[i] = 0;
13         sum[i] = 1;
14     }
15 }
16 
17 int find_set(int x) {
18     int sx = x, ts = 0;
19     while (sx != father[sx]) {
20         ts += trans[sx];
21         sx = father[sx];
22     }
23     int t;
24     while (x != sx) {
25         ts -= trans[x];
26         trans[x] += ts;
27         t = father[x];
28         father[x] = sx;
29         x = t;
30     }
31     return sx;
32 }
33 
34 void union_set(int x, int y) {        // x to y
35     x = find_set(x); y = find_set(y);
36     father[x] = y;
37     trans[x] = 1;
38     sum[y] += sum[x];
39 }
40 
41 int main() {
42 #ifndef ONLINE_JUDGE
43     freopen("in.txt", "r", stdin);
44     freopen("out.txt", "w", stdout);
45 #endif
46     int test;
47     scanf("%d", &test);
48     for (int cas = 1; cas <= test; ++cas) {
49         int n, q;
50         scanf("%d%d", &n, &q);
51         printf("Case %d:\n", cas);
52         init_set(n);
53         for (int i = 0; i < q; ++i) {
54             char c; int a, b;
55             scanf(" %c", &c);
56             if (c == 'T') {
57                 scanf("%d%d", &a, &b);
58                 union_set(a, b);
59             } else {
60                 scanf("%d", &a);
61                 b = find_set(a);
62                 printf("%d %d %d\n", b, sum[b], trans[a]);
63             }
64         }
65     }
66     return 0;
67 }


posted on 2010-09-24 09:19 xpycc 阅读(270) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航:   博客园   博客园最新博文   博问   管理


 
Powered by:
C++博客
Copyright © xpycc