First topology sequencing, then BFS processing
#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <string>
#include <algorithm>
#include <map>
#include <stack>
#include <queue>
#include <vector>
#include <cmath>
#include <utility>
usingnamespaceStd
typedefLongLongLL;
ConstintN =210008, INF =0x3f3f3f3f;
#defineMS (A, num) memset (A, num, sizeof (a))
#definePB (a) push_back (a)
#definefor (i, n) for (int i = 0; i < n; i++)
BOOLVis[n];
structnode{
intTo,next;
}edge[n];
intHead[n], tot, n,m,indeg[n];
intFa[n];
voidInit () {
Memset (Head,-1,sizeof(head));
memset (Indeg,0,sizeof(indeg));
tot =0;
}
voidAddintUintTo) {
indeg[to]++;
Edge[tot].to=to;
Edge[tot].next=head[u];
head[u]=tot++;
}
voidTopsort () {
Stack <int> st;
for(inti =1;i<=n; i++) {
if(indeg[i]==0) {
St.push (i);
}
}
while(!st.empty ()) {
intcur = st.top ();
St.pop ();
Vis[cur] =1;
for(inti = head[cur]; I! =-1; i = edge[i].next) {
intTo= edge[i].to;
indeg[to]--;
if(!indeg[to]) {
St.push (to);
}
}
}
}
voidBFsintu) {
queue<int> q;
Q.push (U);
Vis[u] =1;
while(!q.empty ()) {
intU = Q.front ();
Q.pop ();
for(intI= Head[u]; I! =-1; i = edge[i].next) {
intto = edge[i].to;
if(!vis[to]) {
Vis[to] =1;
Q.push (to);
}
}
}
}
intMain () {
cin>>n;
MS (Vis,0);
Init ();
for(inti =1; I <= n; i++) {
intU
scanf"%d", &u);
Fa[i] = u;
Add (i, u);
}
Topsort ();
intv =0;
for(inti =1; I <= N; i++) {
if(Fa[i] = = i) {
Vis[i] =1;
v = i;
Break;
}
}
if(v = =0){
for(inti =1; I <= N; i++) {
if(!vis[i]) {
Fa[i] = i;
v = i;
Break;
}
}
}
intCNT =0;
for(inti =1; I <= N; i++) {
if(!vis[i]) {
Fa[i] = v;
cnt++;
BFS (i);
}
}
cout<<cnt<<'\ n';
cout<<fa[1];
for(inti =2; I <= n;i++) {
printf"%d", Fa[i]);
}
return0;
}
Codeforces Round #363 Fix A trees (tree topology sort)