NOI 银河英雄传说

并查集水题,记录祖先,大小和深度即可,每次用祖先的大小和深度更新后代的深度。

 1 #include <cstdio>
 2 #include <iostream>
 3 #include <algorithm>
 4 #include <cstring>
 5 using namespace std;
 6 
 7 int n=30000,m,father[30050],d[30050],size[30050];
 8 
 9 int gf(int x) {
10     if (father[x]==x) return x;
11     int k=father[x];
12     father[x]=gf(father[x]);
13     d[x]+=d[k];    
14     return father[x];
15 }
16 
17 int main() {
18     scanf("%d",&m);
19     getchar();
20     for (int i=1; i<=n; i++) father[i]=i;
21     for (int i=1; i<=m; i++) {
22         char opt; 
23         int a,b;
24         scanf(" %c %d%d",&opt,&a,&b);
25         getchar();
26         if (opt=='M') {
27             int fx=gf(a);
28             int fy=gf(b);
29             if (fx!=fy) {
30                 father[fx]=fy;
31                 d[fx]=++size[fy];
32                 size[fy]+=size[fx];
33             } 
34         }else {
35             int fx=gf(a);
36             int fy=gf(b);
37             if (fx!=fy) printf("%d
",-1); else {
38                 if (d[b]>d[a]) printf("%d
",d[b]-d[a]-1); else printf("%d
",d[a]-d[b]-1);
39             }
40         }
41     }
42     return 0;    
43 }
原文地址:https://www.cnblogs.com/zoewilly/p/5991046.html