1. 程式人生 > >CodeForces - 1214D B2. Books Exchange (hard version)

CodeForces - 1214D B2. Books Exchange (hard version)

題目連結:http://codeforces.com/problemset/problem/1249/B2

思路:用並查集模擬連結串列,把關係串聯起來,如果成環,則滿足題意。之後再用並查集合並一個鏈,一個鏈代表

一個集合,一個集合有共同的祖先,一個集合答案相同,則輸出答案時候只需要輸出該元素屬於哪一個集合,那個集合有幾個元素

就可以了。

 1 #include <stdio.h>
 2 #include <iostream>
 3 using namespace std;
 4 
 5 const int N = (int)1e5+100;
 6 int fa[N];
 7 int ans[N];
 8 int root[N];
 9 
10 int search(int x,int& deep){
11 
12     ++deep;
13     if(fa[x] == x) return root[x] = x;
14     else{
15         return root[x] = search(fa[x],deep);
16     }
17 }
18 
19 int main(){
20 
21     int q;
22     scanf("%d",&q);
23 
24     int n,in;
25     while(q--){
26         scanf("%d",&n);
27 
28         for(int i = 1; i <= n; i++){
29             fa[i] = root[i] = i;
30             ans[i] = 0;
31         }
32 
33         int deep = 0;
34         for(int i = 1; i <= n; i++){
35             scanf("%d",&in);
36             deep = 0;
37             if(search(in,deep) == i){
38                 ans[i] = deep;
39             }
40             else fa[i] = in;
41         }
42 
43         printf("%d",ans[root[1]]);
44         for(int i = 2; i <= n; i++) printf(" %d",ans[root[i]]);
45         printf("\n");
46     }
47 
48     return 0;
49 }

&n