题意:有两个黑帮集团,给出一些两个小弟属于不同的黑帮,询问两个小弟是否关系能确定
分析:首先直接弄两个集合是不好的,正确的做法是类似食物链的做法,关系已确定不属于同一个帮派的x 和 y 使得x 和 y + n属于同一个集合,y 和 x + n属于同一个集合,那么最后只要判断x 和 y 是否在同一个集合就可以了
收获:关系的连通问题
代码:
/************************************************
* Author :Running_Time
* Created Time :2015/9/9 星期三 15:17:58
* File Name :O.cpp
************************************************/
#include <cstdio>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <cstring>
#include <cmath>
#include <string>
#include <vector>
#include <queue>
#include <deque>
#include <stack>
#include <list>
#include <map>
#include <set>
#include <bitset>
#include <cstdlib>
#include <ctime>
using namespace std;
#define lson l, mid, rt << 1
#define rson mid + 1, r, rt << 1 | 1
typedef long long ll;
const int N = 2e5 + 10;
const int INF = 0x3f3f3f3f;
const int MOD = 1e9 + 7;
struct UF {
int rt[N], rk[N];
void init(void) {
memset (rt, -1, sizeof (rt));
memset (rk, 0, sizeof (rk));
}
int Find(int x) {
return rt[x] == -1 ? x : rt[x] = Find (rt[x]);
}
void Union(int x, int y) {
x = Find (x), y = Find (y);
if (x == y) return ;
if (rk[x] > rk[y]) {
rt[y] = x; rk[x] += rk[y] + 1;
}
else {
rt[x] = y; rk[y] += rk[x] + 1;
}
}
bool same(int x, int y) {
return Find (x) == Find (y);
}
}uf;
int main(void) {
int T; scanf ("%d", &T);
while (T--) {
int n, m; scanf ("%d%d", &n, &m);
uf.init ();
char s[3];
for (int x, y, i=1; i<=m; ++i) {
scanf ("%s %d %d", &s, &x, &y);
if (s[0] == ‘D‘) {
uf.Union (x, y + n);
uf.Union (x + n, y);
}
else if (s[0] == ‘A‘) {
if (uf.same (x, y)) puts ("In the same gang.");
else if (uf.same (x, y + n)) puts ("In different gangs.");
else puts ("Not sure yet.");
}
}
}
return 0;
}
并查集 POJ 1703 Find them, Catch them
原文:http://www.cnblogs.com/Running-Time/p/4795698.html