[POJ] [1703] Find them, Catch them

Problem Description

Loading...

Problem Analysis

An application of Union-Find
But here we’re told that two people are in different gangs
So we can follow the same approach as the food chain problem
Merge x+n with y, and x with y+n
In the end we only need to check whether x and y, or x+n and y+n
are in the same group

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include<stdio.h>
int par[200200],rank[200200];
int find(int x) {
	if(par[x]==x)
		return x;
	else
		return par[x]=find(par[x]);
}
void unite(int x,int y) {
	x=find(x);
	y=find(y);
	if(x==y)
		return;
	if(rank[x]<rank[y])
		par[x]=y;
	else {
		par[y]=x;
		if(rank[x]==rank[y])
			rank[x]++;
	}
}
int main() {
	int T;
	scanf("%d",&T);
	while(T--) {
		int n,m;
		scanf("%d %d",&n,&m);
		getchar();
		for(int i=1; i<=2*n; i++) {
			par[i]=i;
			rank[i]=0;
		}
		while(m--) {
			char c;
			int x,y;
			scanf("%c %d %d",&c,&x,&y);
			getchar();
			if(c=='D') {
				unite(x,y+n);
				unite(x+n,y);
			} else if(c=='A') {
				if(find(x)==find(y)||find(x+n)==find(y+n))
					printf("In the same gang.\n");
				else if(find(x)==find(y+n)||find(x+n)==find(y))
					printf("In different gangs.\n");
				else
					printf("Not sure yet.\n");
			}
		}
	}
	return 0;
}

Problem link: 【POJ】[1703]Find them, Catch them

This post is licensed under CC BY-NC-SA 4.0. If it helped, or if you have anything to say, the comment box below is open.
Page views —
Unique visitors —

Loading...