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).
View Code
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
相关文章推荐
- runloop
- java连接mysql数据库
- java学习笔记
- Codeforces - Educational Codeforces Round 14C - Exponential notation(模拟)
- 按钮动画
- SDK里报错[NSConcreteMutableData wbsdk_base64EncodedString]
- 通过缓冲区复制文本文件
- 【BZOJ】4300 绝世好题
- mysql-5.7.13在windows上安装使用心得
- SDOI
- MediaPlayer( 媒体播放器),TelephonyManager(电话管理类),MediaRecorder(媒体录音机)
- 一些 DOM 对象方法
- 更新lib文件后jar包存在,报FileNotFound的解决办法:
- Loom工具
- Python新手学习基础之运算符——算术运算符
- Acm 60 谁获得了最高奖学金
- 7.21笔记
- swift - UILabel的用法
- 电子邮件工作机制
- cf #363 c