码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-05-12 09:24:32      阅读:85      评论:0      收藏:0      [点我收藏+]

标签:acm   poj   并查集   


题目传送: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;
}





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

标签:acm   poj   并查集   

原文地址:http://blog.csdn.net/u014355480/article/details/45653187

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!