hdu A Bug's Life 并查集 关系标记
来源:互联网 发布:胡翼青 知乎 编辑:程序博客网 时间:2024/05/16 15:17
题意: 给定一些恋爱关系, 如:a b, 表示a 和 b有暧昧关系, 判断是否能确定有同性恋的存在, 如a喜欢b, b喜欢c, a喜欢c, 则一定存在同性恋,因为a 和 c的性别相同
题解: 用并查集,对于每一个节点a, rel[a]表示a 与 根节点的关系(1表示不同,0表示相同), 如果a 与 b属于同一个集合 且 rel[a] == rel[b] 那么a 与 b 的性别一定相同, 此题的关键在于压缩与联合的时候, 当压缩的时候: rel[a] = (rel[a]+rel[fa[a]])%2, 为什么呢? rel[a]应该保存的是a与根节点的关系,但当还未压缩的时候,rel[a]保存的是a与fa[a]的关系, rel[fa[a]]保存的是fa[a]与根节点的关系, 那么通过当rel[a]==rel[fa[a]]时, rel[a]一定为0, ((1+1)%2=0, (0+0)%2=0,), 当不等的时候,rel[a]一定位1, ((1+0)%2=1), 则以上算式一定是对的, 当联合的时候: 已知a 与 b一定不同, 那么(rel[fa[a]] = rel[a] + rel[b]+1)%2, 为什么呢?用刚才的方法自己在纸上算一下就清楚啦:
code:
#include <cstdio>#include <algorithm>using namespace std;const int maxn = 1e6 + 10;int fa[maxn], rel[maxn], n, m; //rel : 0:same, 1:differentint findSet(int x){ if (x == fa[x]) return x; int father = fa[x]; fa[x] = findSet(fa[x]); rel[x] = (rel[x]+rel[father]) % 2; return fa[x];}void unionSet(int x, int y, int fx, int fy){ fa[fx] = fy; rel[fx] = (rel[x]+rel[y]+1)%2;}bool read_input(){ scanf("%d%d", &n, &m); int flag = 0; for (int i = 1; i <= n; i++) { fa[i] = i, rel[i] = 0; } for (int i = 0; i < m; i++) { int x, y; scanf("%d%d", &x, &y); int fx = findSet(x), fy = findSet(y); if (fx == fy) { if (rel[x] == rel[y]) { flag = 1; } } else { unionSet(x, y, fx, fy); } } return flag;}int main(){ // freopen("/Users/apple/Desktop/in.txt", "r", stdin); int t, kase = 0; scanf("%d", &t); while (t--) { printf("Scenario #%d:\n", ++kase); if (read_input()) puts("Suspicious bugs found!"); else puts("No suspicious bugs found!"); printf("\n"); } return 0;}
0 0
- hdu A Bug's Life 并查集 关系标记
- poj A Bug's Life(关系并查集)
- HDU 1829 A Bug's Life(带关系的并查集)
- 并查集Hdu 1829 A Bug's Life
- HDU 1829 A Bug's Life 并查集
- hdu 1829 A Bug's Life(并查集)
- HDU 1829 A Bug's Life(并查集)
- HDU 1829 A Bug's Life(种类并查集)
- hdu 1829 A Bug's Life (基础并查集)
- HDU 1829 A Bug's Life 并查集
- hdu 1829 A Bug's Life 并查集
- HDU 1829 A Bug's Life (并查集)
- hdu 1829 A Bug's Life 并查集
- hdu 1829 A Bug's Life ( 并查集 )
- hdu 1829 A Bug's Life 并查集
- HDU 1829 A Bug's Life (并查集)
- HDU 1829 A Bug's Life (并查集)
- HDU-1829 A Bug's Life(并查集)
- 物理题 三个芭蕾舞演员 等边三角形
- memcached 相关
- Crocus MF Sensor 应用实例
- 图解GitHub和SourceTree入门教程
- Fragment
- hdu A Bug's Life 并查集 关系标记
- 肉皮三鲜煲的做法
- LeetCode-Search in Rotated Sorted Array
- startActivityForResul完整详解示例
- 2014移动互联网入口之争剧变速度
- cocos2d-x 3.2里lua binding注意事项
- textView 设置右图标
- 个人网站建设基本步骤解析
- 问题:关于一个贴友的js留言板的实现