hdu A Bug's Life 并查集 关系标记
2014-09-14 00:26
267 查看
题意: 给定一些恋爱关系, 如: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:
题解: 用并查集,对于每一个节点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:different int 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; }
相关文章推荐
- Pku acm 2492 A Bug's Life数据结构题目解题报告(十)---- 并查集的应用
- A Bug's Life --- 种类并查集
- POJ 2492 A Bug's Life 并查集维护类别
- [POJ 2492]A Bug's Life[并查集]
- POJ2492A Bug's Life【并查集+根节点偏移】
- POJ 2492--A Bug's Life 【并查集,向量偏移】
- HDU1829 - A Bug's Life 分组并查集
- POJ-2492 A Bug's Life 并查集
- poj 2492 A Bug's Life 【并查集拓展】
- hdoj 1829 A Bug's Life 【带权并查集】
- POJ 2492 A Bug's Life 并查集的应用
- poj 2492 A BUG'S LIFE 不是纯裸的并查集
- HDU1829 A Bug's Life 并查集
- POJ P2492 A Bug's Life 并查集
- POJ 2492 A Bug's Life 并查集
- hdu 1829 A Bug's Life 并查集
- 【图论05】并查集 1004 A Bug's Life
- A Bug's Life 【POJ--2492】【带权的并查集】
- HDU 1829 A Bug's Life 并查集
- POJ2492(A Bug's Life) && POJ1703(Find them, Catch them)带权(种类)并查集