POJ 虫子的生活 解题报告 (种类并查集)
2017-12-13 20:08
537 查看
POJ 虫子的生活 解题报告
题目链接: http://dsalgo.openjudge.cn/tree/10/思路:
这种涉及到多个类别(在这里的意思是产生过相互关系的虫子),和少量集合(这里指性别)的题目,我想到的是使用并查集,但是基础的并查集并不能解决这种问题,因为这里有两种类(类别和集合),应该使用升级版的种类并查集。
种类并查集的两个要点是:
1. 处理集合
2. 更新集合
我把实现细节放在了代码里:
#include <cstdio> int Set[2010]; //并查集的父节点 int relaWithFarther[2010]; //记录与父节点的关系 0 same Sex, 1 diff Sex bool suspicious; void ini() { suspicious = false; for(int i = 0; i < 2010; ++i) { Set[i] = i; relaWithFarther[i] = 0; } } int find(int node) { if(Set[node] == node) return node; int end = find(Set[node]); relaWithFarther[node] = relaWithFarther[node] ^ relaWithFarther[Set[node]]; //到这里node的父节点的父节点已经压缩到了end,node与end的关系可以由node与其现在的父节点的关系以及Set[node]与其父节点的关系推出来。 Set[node] = end; return end; } void Union(int nodeA, int nodeB) { int endA = find(nodeA); int endB = find(nodeB); //注意因为路径压缩,nodeA和nodeB的父节点已经转变。 if(endA == endB) { if(relaWithFarther[nodeA] == relaWithFarther[nodeB])//同性 { suspicious = true; return ; } } //此时保证了非同性 Set[endA] = endB; relaWithFarther[endA] = relaWithFarther[nodeA] ^ relaWithFarther[nodeB] ^ 1; //同理推出更新规则 } int main() { int cases; int m, n; int nodeA, nodeB; scanf("%d", &cases); for(int t = 1; t <= cases; ++t) { ini(); scanf("%d %d", &m, &n); for(int i = 0; i < n; ++i){ scanf("%d %d", &nodeA, &nodeB); Union(nodeA, nodeB); } printf("Scenario #%d:\n", t); if(suspicious){ printf("Suspicious bugs found!\n\n"); }else{ printf("No suspicious bugs found!\n\n"); } } return 0; }
相关文章推荐
- Poj 食物链 解题报告 (种类并查集)
- 【解题报告】 POJ 1611 The Suspects 并查集基础 (一点自己的感悟)
- POJ 2524 Ubiquitous Religions 解题报告(并查集)
- POJ 2513 Colored Sticks (Trie字典树+欧拉通路+并查集) 解题报告
- poj 1182 食物链(并查集)解题报告(转)
- poj 1733 Parity game 并查集 解题报告
- poj 1417 True Liars 解题报告 并查集 DP
- 【原】 POJ 1308 Is It A Tree? 并查集树结构 解题报告
- 并查集(种类并查集)POJ2492A Bug's Life解题报告
- poj 3728 LCA+并查集 解题报告
- POJ3228 Gold Transportation 解题报告【贪心+并查集=Kruskal?】
- POJ 1182 并查集 解题报告
- 【原】 POJ 1611 The Suspects 并查集 解题报告
- poj 1984 Navigation Nightmare 并查集 解题报告
- openoj的一个小比赛(J题解题报告)poj1703(并查集)
- poj 3228 Gold Transportation 最小生成树+带权并查集 解题报告
- 【解题报告】 POJ 1182 食物链 并查集的经典应用+相对位置
- PKU POJ 1611解题报告(并查集)
- poj 1182 食物链(并查集)解题报告(转)
- 【解题报告】 POJ 1308 Is It A Tree? 并查集判断一棵树