Codeforces--Books Exchange (hard version)

Topic Link http://codeforces.com/contest/1249/problem/B2  . Disjoint-set ideas, divided into a number of sets, each the size of the collection is the number of days required round.

Map [i] storing data.

In Flag [i] indicates whether the i-th to be accessed.

mm [i] records the i-th set corresponding to the size of the set, the index i is the i-th root of the corresponding set of values.

GetParent recursive method on the idea of ​​updating each node relay, directly to the root of the current collection.

Since no set of visited access, therefore, the analysis time complexity, accuracy is O (CN), C is a constant. It should be noted here that, mm To clean after each use, otherwise there will be problems.

 1 #include<bits/stdc++.h>
 2 
 3 /*
 4 * 并查集
 5 */
 6 
 7 using namespace std;
 8 
 9 static const int MAX = 200005;
10 
11 int Map[MAX];
12 bool flag[MAX];
13 map<int, int> mm;
14 
15 int getParent(int x){
16     if(!flag[x]){
17         flag[x] = true;
18         Map[x] = getParent(Map[x]);
19     }
20     return Map[x];
21 }
22 
23 int main(){
24     int q;
25     scanf("%d", &q);
26     while(q--){
27         int n;
28         scanf("%d", &n);
29         for(int i=1;i<=n;i++){
30             flag[i] = false;
31         }
32 
33         // construct set
34         int tmp;
35         for(int i=1;i<=n;i++){
36             scanf("%d", &Map[i]);
37         }
38 
39         // solve
40         for(int i=1;i<=n;i++){
41             int parent = getParent(i);
42             mm[parent]++;
43         }   
44 
45         for(int i=1;i<=n;i++){
46             if(i==1){
47                 printf("%d", mm[Map[i]]);
48             }
49             else{
50                 printf(" %d", mm[Map[i]]);
51             }
52         }
53         printf("\n");
54         mm.clear();
55     }
56     return 0;
57 }

 

Guess you like

Origin www.cnblogs.com/sgatbl/p/11746984.html