您的位置:首页 > 其它

POJ - 1703 - Find them, Catch them (并查集)

2015-05-12 00:04 441 查看
题目传送:Find them, Catch them

思路:用一个关系数组记录当前结点与其父亲的关系,0表示同类,1表示不同类

AC代码:

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <set>
#include <deque>
#include <cctype>
#define LL long long
#define INF 0x7fffffff
using namespace std;

const int maxn = 100005;
int T;
int n, m;
int pa[maxn];
int rela[maxn];//±íʾ½áµãÓëÆ丸Ç׵ĹØϵ£¬Í¬ÀàΪ0£¬²»Í¬ÀàΪ1£¬³õʼʱͬÀà 

int find(int x) {
	int t = pa[x];
	if(pa[x] == x) {
		return x;
	}
	else {
		pa[x] = find(pa[x]);
		rela[x] = (rela[x] == rela[t]) ? 0 : 1;//µÈÓÚ0±íʾÊôÓÚͬһÀà 
		return pa[x];
	}
}

int main() {
	scanf("%d", &T);
	while(T --) {
		scanf("%d %d", &n, &m);
		for(int i = 1; i <= n; i ++) { //³õʼ»¯ 
			pa[i] = i;
			rela[i] = 0;
		}
		for(int i = 0; i < m; i ++) {
			int a, b;
			char op[5];
			scanf("%s %d %d", op, &a, &b);
			int fa = find(a), fb = find(b);
			if(op[0] == 'A') {
				if(fa != fb) {
					printf("Not sure yet.\n");
				}
				else if(rela[a] == rela[b]){
					cout << "In the same gang." << endl;
				}
				else {
					cout << "In different gangs." << endl;
				}
			}
			else {
				if(fa != fb) {
					pa[fa] = fb;
					rela[fa] = (rela[a] == rela[b]) ? 1 : 0;//a,b¿Ï¶¨²»ÔÚͬһ¸ö°ïÅÉ 
				}
			}
		}
	}
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: