Ring disjoint-set minimum requirements

Example: Luo Guxin information transfer

The minimum required is 2015 NOIP ring of a question, as I do not Tacca This question, after reading the explanations make a note of it!

 

After requires a minimum loop we have to find all of the ring, the ring way is to find a father i read, whether or not They now have connected, even if already on, then form a ring, not at this time they then need to connect the two, otherwise it will die cycle, then it is estimated that some people will ask, do not connect them, so if there is a ring that contains this edge is smaller than you now do not you ring it wrong ? (This is a special figure this question, because there is a father for every point only, as we traverse point of view, so in this case i and the father of i 's father already knew, then it can no longer be after this there are other sides of the ring), of course, at this time, if the father took a different incorporated i

 

 

 1 #include<iostream>
 2 #include<vector>
 3 #include<algorithm>
 4 #include<cstring>
 5 #include<climits>
 6 using namespace std;
 7 int fa[200010];
 8 int res=INT_MAX;
 9 int cnt=0;
10 int find(int x)
11 {
12     cnt++;
13     if(fa[x]==x)
14         return fa[x];
15     else
16         return find(fa[x]);
17 }
18 int main()
19 {
20     int n;
21     cin>>n;
22     for(int i=1;i<=n;i++)
23         fa[i]=i;
24     for(int i=1;i<=n;i++)
25     {
26         cnt=0;
27         int t;
28         cin>>t;
29         if(find(t)==i)
30         {
31             res=min(res,cnt);
32         }
33         else
34         {
35             fa[i]=t;
36         }
37     }
38     cout<<res;
39     return 0;
40 }

 

 

 

Guess you like

Origin www.cnblogs.com/greenofyu/p/12002362.html