Problem - D - Codeforces Fix a Tree
2016-07-20 12:44
162 查看
Problem - D - Codeforces Fix a Tree
看完第一名的代码,顿然醒悟。。。
我可以把所有单独的点全部当成线,那么只有线和环。
如果全是线的话,直接线的条数-1,便是操作数。
如果有环和线,环被打开的同时,接入到线上。那就是线和环的总数-1.
如果只有环的话,把所有的环打开,互相接入,共需n次操作。
看完第一名的代码,顿然醒悟。。。
我可以把所有单独的点全部当成线,那么只有线和环。
如果全是线的话,直接线的条数-1,便是操作数。
如果有环和线,环被打开的同时,接入到线上。那就是线和环的总数-1.
如果只有环的话,把所有的环打开,互相接入,共需n次操作。
#include <cstdio> #include <algorithm> using namespace std; const int maxn = 2e5+5; int cur[maxn]; int pre[maxn]; int Find(int x) {return pre[x] == x ? x : Find(pre[x]);} int main() { int n; scanf("%d",&n); int thread = 0; int ans = 0; for(int i = 1; i<=n; i++) pre[i] = i; for(int i = 1; i<=n; i++) { scanf("%d",&cur[i]); if(cur[i]==i) { thread = i; ans++; } else { int fx = Find(i); int fy = Find(cur[i]); if(fx == fy) { cur[i] = i; ans++; } else { pre[fx] = fy; } } } if(thread==0) //全是环 { for(int i = 1; i<=n; i++) { if(cur[i]==i) { thread = i; break; } } ans++; } printf("%d\n",ans-1); for(int i = 1; i<=n; i++) { if(cur[i]==i) cur[i] = thread; } for(int i = 1; i<n; i++) printf("%d ",cur[i]); printf("%d\n",cur ); return 0; }
相关文章推荐
- jquery性能
- MFC学习笔记——解决:不能添加控件变量
- JavaScript random方法得到随机整数
- iOS核心动画-UIView封装动画
- hdu5723(16多校第1场,树上两点平均距离的期望)
- 《圣经》故事与典故
- 在VUX中使用自定义组件要注意scroller组件等vux组件的覆盖
- 陪审团制度
- python基础之 Python os._exit() sys.exit() exit()区别
- CSS样式自动换行(强制换行)与强制不换行
- httpoxy 漏洞预警及修复方案
- 大整数类模板
- 负载均衡-会话保持,session同步(转载)
- uva 401 回文词
- 在SQLserver中stuff 函数用法
- 可变參函数设计
- NSUserDefaults 的使用
- 监听开关机,发送广播
- Codeforces Round #363 (Div. 2) B 暴力
- 【HDU】5468 Puzzled Elena