poj 1611 - The Suspects(并查集)
来源:互联网 发布:机柜网络模块接线图 编辑:程序博客网 时间:2024/05/01 19:48
传说中的大水题,我却纠结了好久。
原因是我的思路逻辑上有点有bug。
思路:
很明显的并查集题目,把每组的成员都放到一个集合里面,然而我为了保证符合条件的答案都在0这个集合中,所以我对每个分组都是合并到改组中编号最小的那个节点上了,恰恰是这个想法成了我代码的bug,出错的原因是每组的节点都合并到了最小的点上,但并不能保证合并后的那个集合的节点是编号最小的,因为这还牵扯到父节点的问题。
例如某个分组中有10,100两个成员,然后p[10] = 9; p[100] = 0;而我的代码在这个case下就犯错了,把0节点的那个集合并到了9那个集合中。
代码如下:
const int M = 30005;int p[M];int find(int x) { return p[x] == x ? x : p[x] = find(p[x]); }int main(){ int n, m, k, x, lastx; while(scanf("%d%d", &n, &m) && n+m) { for(int i = 0; i <= n; ++i) p[i] = i; for(int i = 0; i < m; ++i) { scanf("%d%d", &k, &lastx); for(int j = 1; j < k; ++j) { scanf("%d", &x); int a = find(lastx); int b = find(x); if(a>b) p[a] = b; //错误代码此处是:if(a != b && x < lastx) p[a] = b; else p[b] = a; //错误代码此处是:if(a != b && x > lastx) p[b] = a; lastx = x; } } int ans = 0; for(int i = 0; i < n; ++i) ans += (find(i)==0); printf("%d\n", ans); } return 0;}
- POJ 1611 The Suspects(并查集)
- poj 1611 The Suspects 并查集
- POJ 1611 The Suspects 并查集
- poj 1611 The Suspects(并查集)
- POJ 1611 The Suspects 并查集
- POJ--1611--The Suspects【并查集】
- poj 1611-The Suspects:并查集
- POJ--1611 -- The Suspects [并查集]
- poj 1611 - The Suspects(并查集)
- poj 1611The Suspects 并查集
- poj 1611 The Suspects 并查集
- [并查集]POJ 1611 The Suspects
- poj 1611 The Suspects --- 并查集
- POJ 1611 The Suspects (并查集)
- POJ 1611 The Suspects(并查集)
- POJ 1611--The Suspects 并查集
- POJ 1611 The Suspects 并查集
- poj 1611 The Suspects(并查集)
- POJ 1220 (两种任意进制之间的转换(大数),java的BigInteger)
- linux_source_0_11
- struts.xml配置文件中的action的各项默认值
- 关于submit和button在javaScript中的区别
- 女扒手在内衣店中被抓时购物袋里装着死婴
- poj 1611 - The Suspects(并查集)
- 魏小亮:国内软件工程师如何面试硅谷创业公司
- iOS7中的ViewController切换
- 关于酷派8730“移动版”手机无法将应用安装在外置SD卡的解决办法和获取ROOT权限方法
- HDU-2222-Aho-Corasick--自动机
- 魏小亮:如何选择硅谷的IT公司
- 【Cocosd2d实例教程六】Cocos2d实现屏幕背景的自动滚动
- eclipse快捷键——Ctrl+Shift+F 格式化当前代码
- UMX Viewer