698B - Fix a Tree - CodeForces Solution


constructive algorithms dfs and similar dsu graphs trees *1700

Please click on ads to support us..

C++ Code:

#include<bits/stdc++.h>
using namespace std;
int n,a[200001],b[200001],c[200001],r,g;
int dfs(int x){
	if(c[x])return c[x];
	if(b[x])return c[x]=x;
	b[x]=1;
	return c[x]=dfs(a[x]);
}
int main(){
	cin>>n;
	for(int i=1;i<=n;i++)cin>>a[i];
	for(int i=1;i<=n;i++)dfs(i);
	for(int i=1;i<=n;i++)if(a[i]==i&&c[i]==i)r=i;
	if(!r){
		for(int i=1;i<=n;i++){
			if(c[i]!=i)continue;
			g++;
			a[i]=r=i;
			break;
		}
	}
	for(int i=1;i<=n;i++)if(c[i]==i)g++,a[i]=r;
	cout<<g-1<<endl;
	for(int i=1;i<=n;i++)cout<<a[i]<<' ';
	return 0;
}


Comments

Submit
0 Comments
More Questions

265A - Colorful Stones (Simplified Edition)
296A - Yaroslav and Permutations
967B - Watering System
152A - Marks
1398A - Bad Triangle
137A - Postcards and photos
1674D - A-B-C Sort
334A - Candy Bags
855A - Tom Riddle's Diary
1417A - Copy-paste
1038A - Equality
1061A - Coins
1676E - Eating Queries
1447A - Add Candies
1721D - Maximum AND
363C - Fixing Typos
1401A - Distance and Axis
658A - Bear and Reverse Radewoosh
1721E - Prefix Function Queries
977E - Cyclic Components
1140D - Minimum Triangulation
75C - Modified GCD
1722A - Spell Check
1722B - Colourblindness
1722D - Line
1722C - Word Game
1722G - Even-Odd XOR
552E - Vanya and Brackets
933A - A Twisty Movement
1722F - L-shapes