POJ 1703 Find them, Catch them

并查集应用

#include <stdio.h>

typedef struct node{
	int father;
	bool same_group;
}node;

node arr[100005];

void init(int n){
	int i;
	for(i=1; i<=n; i++){
		arr[i].father = i;
		arr[i].same_group = true;
	}
}

int find_father(int son){
	int last_father;

	if(son == arr[son].father)
		return son;

	last_father = arr[son].father;
	arr[son].father = find_father(last_father);

	if(arr[last_father].same_group == arr[son].same_group)
		arr[son].same_group = true;
	else
		arr[son].same_group = false;

	return arr[son].father;
}

void merge(int a, int b, int father_a, int father_b){
	//a和b不在一个队,那么如果a和father_a以及b和father_b的关系是一样的,那么father_a和father_b一定不在一个队里面
	arr[father_a].father = father_b;
	if(arr[a].same_group == arr[b].same_group)
		arr[father_a].same_group = false;
	else
		arr[father_a].same_group = true;
}

char tmp[1000];
char cmd[1000];


#pragma warning(disable:4996)
int main(void){
	int case_n, cri_n, cmd_n, i;
	int cri_a, cri_b;
	int father_a, father_b;

	//freopen("input.dat", "r", stdin);
	scanf("%d", &case_n);
	while(case_n--){
		scanf("%d %d", &cri_n, &cmd_n);
		init(cri_n);
		for(i=0; i<cmd_n; i++){
			scanf("%s %d %d", cmd, &cri_a, &cri_b);
			father_a = find_father(cri_a);
			father_b = find_father(cri_b);

			if('A' == cmd[0]){
				if(father_a !=father_b){
					printf("Not sure yet.\n");
				}
				else{
					if(arr[cri_a].same_group == arr[cri_b].same_group){
						printf("In the same gang.\n");
					}
					else{
						printf("In different gangs.\n");
					}
				}
			}
			else{
				if(father_a != father_b)
					merge(cri_a, cri_b, father_a, father_b);
			}
		}
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值