您的位置:首页 > 其它

cf #363 d

2016-07-21 09:53 190 查看
time limit per test
2 seconds

memory limit per test
256 megabytes

input
standard input

output
standard output

A tree is an undirected connected graph without cycles.

Let's consider a rooted undirected tree with n vertices, numbered 1 through n. There are many ways to represent such a tree. One way is to create an array with n integers p1, p2, ..., pn, where pi denotes a parent of vertex i (here, for convenience a root is considered its own parent).

#include<iostream>
#include<stdio.h>
#define maxx 200005
using namespace std;
int root=0;
int ci=1;
int ans=0;
int a[maxx];
int vis[maxx];
void find(int x){
vis[x]=ci;
while(!vis[a[x]]){
x=a[x];
vis[x]=ci;
}
if(vis[a[x]]==ci){
if(root==0){
root=x;
}
if(a[x]!=root){
a[x]=root;
ans++;
}
}
ci++;
}
int main(){
int n;
scanf("%d",&n);
for(int i=0;i<=n;i++) vis[i]=0;
for(int i=1;i<=n;i++){
scanf("%d",&a[i]);
if(i==a[i]) root=i;

}
for(int i=1;i<=n;i++){
if(!vis[i]){
find(i);
}
}
printf("%d\n",ans);
for(int i=1;i<n;i++){
printf("%d ",a[i]);
}
printf("%d\n",a
);
return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: