POJ 1703 Find them, Catch them (种类并查集)
作者:互联网
题目传送:POJ 1703
Describe: |
The police office in Tadu City decides to say ends to the chaos, as launch actions to root up the TWO gangs in the city, Gang Dragon and Gang Snake. However, the police first needs to identify which gang a criminal belongs to. The present question is, given two criminals; do they belong to a same clan? You must give your judgment based on incomplete information. (Since the gangsters are always acting secretly.) Assume N (N <= 10^5) criminals are currently in Tadu City, numbered from 1 to N. And of course, at least one of them belongs to Gang Dragon, and the same for Gang Snake. You will be given M (M <= 10^5) messages in sequence, which are in the following two kinds: 1. D [a] [b] where [a] and [b] are the numbers of two criminals, and they belong to different gangs. 2. A [a] [b] where [a] and [b] are the numbers of two criminals. This requires you to decide whether a and b belong to a same gang. |
Input: |
The first line of the input contains a single integer T (1 <= T <= 20), the number of test cases. Then T cases follow. Each test case begins with a line with two integers N and M, followed by M lines each containing one message as described above. |
Output: |
For each message "A [a] [b]" in each case, your program should give the judgment based on the information got before. The answers might be one of "In the same gang.", "In different gangs." and "Not sure yet." |
Sample Input: |
1 5 5 A 1 2 D 1 2 A 1 2 D 2 4 A 1 4 |
Sample Output: |
Not sure yet. In different gangs. In the same gang. |
题目大意:
城市有两个帮派,有两种指令,D a b表示a,b不在同一个帮派,A a b表示询问a,b是否在一个帮派。
解题思路:
mergeset(a,b+n);用来表示a和b不是一个帮派,查询时按结果输出即可。
AC代码:
1 #include <iostream> 2 #include <cstdio> 3 #define N 100010 4 using namespace std; 5 // 以下四个函数均为并查集模板 6 int a[2*N],r[2*N]; 7 void init(int n) 8 { 9 for(int i = 0; i <= n; i++) 10 { 11 a[i] = i; 12 r[i] = 1; 13 } 14 } 15 int findset(int x) 16 { 17 return a[x] == x?x:(a[x] = findset(a[x])); 18 } 19 void mergeset(int x, int y) 20 { 21 x = findset(x); y = findset(y); 22 if(x != y) 23 { 24 if(r[x] <= r[y]) a[x] = y; 25 else a[y] = x; 26 if(r[x] == r[y]) r[y]++; 27 } 28 } 29 bool issame(int x, int y) 30 { 31 return findset(x) == findset(y); 32 } 33 int main() 34 { 35 int t,m,n,x,y; 36 char c; // 各种所需变量 37 scanf("%d",&t); 38 while(t--) 39 { 40 scanf("%d%d",&n,&m); 41 init(2*n); // 两个帮派,所以开大两倍 42 while(m--) 43 { 44 scanf("\n%c%d%d",&c,&x,&y); // Attention! 输入字符前加一个换行符 45 if(c == 'D') 46 { 47 mergeset(x,y+n); // 可以理解为x和y的敌人是一个帮派的,即敌人的敌人是朋友 48 mergeset(x+n,y); 49 } else if(c == 'A') { 50 if(issame(x,y+n) || issame(x+n,y)) printf("In different gangs.\n"); 51 else if(issame(x,y) || issame(x+n,y+n)) printf("In the same gang.\n"); 52 else printf("Not sure yet.\n"); 53 } 54 } 55 } 56 return 0; 57 }
标签:them,1703,gangs,查集,two,same,criminals,gang,帮派 来源: https://www.cnblogs.com/gblong10/p/13469181.html