LA 3644 并查集判断无向图是否有环
2015-08-24 10:31
288 查看
理解清楚题意以后就明白为什么要用并查集了。
#include <iostream> #include <cstring> #include <cstdio> using namespace std; const int N = 100001; int f ; int ans; void init() { ans = 0; for ( int i = 0; i < N; i++ ) { f[i] = i; } } int findf( int x ) { if ( f[x] != x ) f[x] = findf( f[x] ); return f[x]; } bool union_set( int x, int y ) { x = findf(x), y = findf(y); if ( x == y ) return false; f[x] = y; return true; } int main () { int x, y; while ( scanf("%d%d", &x, &y) != EOF ) { init(); f[x] = y; while ( scanf("%d", &x), x != -1 ) { scanf("%d", &y); if ( !union_set( x, y ) ) { ans++; } } printf("%d\n", ans); } return 0; }
相关文章推荐
- java 源码中T的含义
- 九度oj1515打印1到最大的N位数
- [leetcode] 268.Missing Number
- POJ 1484 Blowing Fuses(水~)
- ACM Computer Factory(POJ--3436
- POJ--1995--Raising Modulo Numbers
- Linux命令: cut命令的使用方法
- 制造并批量生产现实版“储物戒指”
- 【LeetCode】268 Missing Number
- [LeetCode] House Robber
- 8月20日全球六大国际域名解析量变化情况统计报告
- performSegue的执行过程
- 专车动态加价太高乘客不爽:最高加价4.75倍
- Hibernate关系映射总结
- 黑马程序员_java基础之IO流(一)
- 实习笔记6
- java中substring的用法
- 网页版上拉加载
- POJ 1477 && HDU 1326 Box of Bricks(水~)
- OpenCV和Cuda结合编程