http://poj.org/problem?id=1703
2.Idea
Using Union-Find set.
3.Source
int Parent[200005];
int Size[200005];
int n, m;
void make_set(int v) {
Parent[v] = v;
Size[v] = 1;
}
int find_set(int v) {
if (v == Parent[v])
return v;
return Parent[v] = find_set(Parent[v]);
}
void union_sets(int a, int b) {
a = find_set(a);
b = find_set(b);
if (a != b) {
if (Size[a] < Size[b])
swap(a, b);
Parent[b] = a;
Size[a] += Size[b];
}
}
int main()
{
int t;
cin >> t;
while (t--) {
cin >> n >> m;
for (int i = 1; i <= 2 * n; i++) make_set(i);
char c;
int a, b;
for (int i = 0; i < m; i++) {
scanf(" %c %d %d", &c, &a, &b);
//cin >> c >> a >> b;
if (c == 'D') {
union_sets(a, b + n);
union_sets(b, a + n);
}
else {
if (find_set(a) == find_set(b) || find_set(a + n) == find_set(b + n)) {
puts("In the same gang.");
}
else if (find_set(a) == find_set(b + n) || find_set(a + n) == find_set(b)) {
puts("In different gangs.");
}
else {
puts("Not sure yet.");
}
}
}
}
return 0;
}
No comments:
Post a Comment