poj 1703 Find them, Catch them(带权并查集)
2014-04-22 23:13
369 查看
题目: poj 1703 Find them, Catch them(带权并查集)
题目大意:题目已知有两个帮派,D x y 代表这两个属于不同的帮派,A X Y 是询问X Y 属于相同还是不同还是不确定的帮派。
解题思路:这题要用到带权并查集,例如 c【x】= 1 的话就说明他与根是不属于同一个帮派的,0就反之。 每次给出一个D X Y 的话就需要把 c【q】 = ( c[x] + c[y] + 1 ) % 2; 例如如果x, y属于不同的帮派,然后x与他的根属于相同的帮派,y 与他的根属于不同的帮派,那么 q 和p 就是属于相同的帮派, c【q】 = (1 + 0 + 1) % 2 = 0;
代码:
题目大意:题目已知有两个帮派,D x y 代表这两个属于不同的帮派,A X Y 是询问X Y 属于相同还是不同还是不确定的帮派。
解题思路:这题要用到带权并查集,例如 c【x】= 1 的话就说明他与根是不属于同一个帮派的,0就反之。 每次给出一个D X Y 的话就需要把 c【q】 = ( c[x] + c[y] + 1 ) % 2; 例如如果x, y属于不同的帮派,然后x与他的根属于相同的帮派,y 与他的根属于不同的帮派,那么 q 和p 就是属于相同的帮派, c【q】 = (1 + 0 + 1) % 2 = 0;
代码:
#include <stdio.h> const int N = 100005; int t, n, m, f , c ; void init () { for (int i = 0; i <= n; i++) { f[i] = i; c[i] = 0; } } int getfather (int x) { if ( x == f[x] ) return x; else { int t = f[x]; f[x] = getfather (f[x]); c[x] = (c[x] + c[t]) % 2; return f[x]; } } int main () { scanf ("%d", &t); int x, y; while (t--) { scanf ("%d%d", &n, &m); init(); char s[10]; for (int i = 0; i < m; i++) { scanf ("%s", s); if (s[0] == 'D') { scanf ("%d%d", &x, &y); int p = getfather(x); int q = getfather(y); f[p] = q; c[p] = (c[y] + c[x] + 1) % 2; } else { scanf ("%d%d", &x, &y); int p = getfather(x); int q = getfather(y); if (p != q) printf("Not sure yet.\n"); else if (c[x] == c[y]) printf ("In the same gang.\n"); else printf ("In different gangs.\n"); } } } }
相关文章推荐
- poj 1703 Find them, Catch them 【带权并查集】
- POJ 1703 Find them, Catch them(并查集的扩展应用)
- poj 1703 Find them, Catch them (并查集)
- poj 1703 Find them, Catch them(种类并查集)
- poj1703 Find them, Catch them(种类并查集
- POJ 1703 Find them, Catch them[并查集]
- hdu - 1829 A Bug's Life (并查集)&&poj - 2492 A Bug's Life && poj 1703 Find them, Catch them
- POJ 1703 Find them, Catch them(种类并查集)
- poj--1703--Find them, Catch them(并查集巧用)
- POJ 1703 Find them, Catch them 种类并查集(入门)
- (用树结构支持并查集8.2.2)POJ 1703 Find them, Catch them(并查集的简单使用: 判断两个元素是否属于同一集合)
- POJ1703 Find them, Catch them 【并查集】
- POJ 1703-Find them, Catch them(并查集)
- POJ 1703 Find them, Catch them【并查集】
- POJ 1703 Find them,Catch them ----种类并查集(经典)
- POJ 1703 Find them, Catch them 关系并查集
- poj 1703 Find them, Catch them 并查集
- 【POJ 1703】 Find them, Catch them(关系并查集)
- poj 1703 Find them, Catch them(并查集)
- poj--1703--Find them, Catch them(并查集巧用)