Luo Gu P2661 messaging solution to a problem

Daily questions day3 punch

Analysis

Disjoint-set requirements with the smallest ring with the smallest ring cnt record length.

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<algorithm>
 5 #define maxn 200010
 6 #define INF 2147483647/2-1
 7 using namespace std;
 8 inline int read()
 9 {
10     int x=0;
11     bool f=1;
12     char c=getchar();
13     for(; !isdigit(c); c=getchar()) if(c=='-') f=0;
14     for(; isdigit(c); c=getchar()) x=(x<<3)+(x<<1)+c-'0';
15     if(f) return x;
16     return 0-x;
17 }
18 inline void write(int x)
19 {
20     if(x<0){putchar('-');x=-x;}
21     if(x>9)write(x/10);
22     putchar(x%10+'0');
23 }
24 int n,ans=INF;
25 int prt[maxn];
26 inline int find(int x,int &cnt)
27 {
28     cnt++;
29     if(prt[x]==x) return x;
30     else return find(prt[x],cnt);
31 }
32 int main()
33 {
34     n=read();
35     for(int i=1;i<=maxn;i++) prt[i]=i;
36     for(int i=1;i<=n;i++)
37     {
38         int T,cnt=0;
39         T=read();
40         if(find(T,cnt)==i) ans=min(ans,cnt);
41         else prt[i]=T;
42     }
43     write(ans);
44     return 0;
45 } 

Please Gangster treatise(Anyway, I do not know what that means treatise)

Guess you like

Origin www.cnblogs.com/handsome-zyc/p/11300148.html