POJ 1703 - Find them, Catch them
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:
D [a] [b]
where [a] and [b] are the numbers of two criminals, and they belong to different gangs.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.
題意:一個(gè)城市有兩個(gè)幫派酸些,現(xiàn)在公安局掌握了一些資料肛炮,但是只知道A,B兩個(gè)屬于不同的幫派。要你根據(jù)所給的信息判別任意兩個(gè)人的關(guān)系,是屬于同一個(gè)幫派還是屬于不同的幫派咽笼,還是他們的關(guān)系不能確定了?
解題思路:
食物鏈的簡化版
A x y 不能確定xy是否是同一幫派
D x y 確定xy屬于不同幫派
x表示幫派A x+n表示幫派B
#include <stdio.h>
#include <iostream>
#include <string.h>
using namespace std;
const int N = 100000;
const int MAX = 2*N+16;
int fa[MAX], deep[MAX];
void init()
{
memset(fa, -1, sizeof(fa));
memset(deep, 0, sizeof(deep));
}
int find(int x)
{
if (fa[x] == -1) return x;
return fa[x] = find(fa[x]);
}
void unite(int x, int y)
{
x = find(x), y = find(y);
if (x == y) return;
if (deep[x]<deep[y])
fa[x] = y;
else
{
fa[y] = x;
if (deep[x] == deep[y])
deep[x]++;
}
}
bool same(int x, int y)
{
return find(x) == find(y);
}
int main()
{
int T;
scanf("%d", &T);
while (T--) {
int n, m;
int x, y;
char c[2];//這里如果定義char c 會出現(xiàn)Runtime Error
if (T >= 20) break;
scanf("%d%d", &n, &m);
init();
//cin>>n>>m;
if (n>N || m>N) break;
while (m--) {
scanf("%s%d%d", c, &x, &y);
//cin >> c >> x >> y;
if (c[0] == 'D')
{
unite(x, y + n);
unite(x + n, y);
}
else {
if (same(x, y) || same(x + n, y + n))
{
printf("In the same gang.\n");
continue;
}
if (same(x, y + n) || same(x + n, y))
{
printf("In different gangs.\n");
continue;
}
printf("Not sure yet.\n");
}
}
}
return 0;
}