Problem-d-Codeforces Fix a Tree
After reading the first name of the code, suddenly wake up ...
I can take all the individual points as lines, then only the lines and loops.
If all lines, the number of direct lines-1, is the operand.
If there is a ring and a line, the ring is opened at the same time, connected to the line. That is the total number of lines and rings-1.
If only the ring, put all the rings open, mutual access, total need n operations.
#include <cstdio>#include<algorithm>using namespacestd;Const intMAXN = 2e5+5;intCUR[MAXN];intPRE[MAXN];intFind (intx) {returnPRE[X] = = x?X:find (pre[x]);}intMain () {intN; scanf ("%d",&N); intThread =0; intAns =0; for(inti =1; i<=n; i++) Pre[i] =i; for(inti =1; i<=n; i++) {scanf ("%d",&Cur[i]); if(cur[i]==i) {thread=i; Ans++; } Else { intFX =Find (i); intFY =Find (Cur[i]); if(FX = =FY) {Cur[i]=i; Ans++; } Else{PRE[FX]=fy; } } } if(thread==0)//It's all rings . { for(inti =1; i<=n; i++) { if(cur[i]==i) {thread=i; Break; }} ans++; } printf ("%d\n", ans-1); for(inti =1; i<=n; i++) { if(cur[i]==i) Cur[i] =thread; } for(inti =1; i<n; i++) printf ("%d", Cur[i]); printf ("%d\n", Cur[n]); return 0;}
Problem-d-Codeforces Fix a Tree