poj 1703

来源:互联网 发布:macbook视频拼接软件 编辑:程序博客网 时间:2024/05/16 14:24

并查集。
用一个opposite数组保存一个人a的对立人。对于输入的一个人b和c,只要判断b和opposite[c]是否是一组就好了。
也可以不用opposite数组,把并查集开到2倍的大小,用前n个保存数据,使用后n个作为opposite,一样的。

#include <iostream>using namespace std;const int MAX_NUM = 10000005;int n, m, t;int par[MAX_NUM], rank[MAX_NUM], opposite[MAX_NUM];void init(int n) {    for(int i=0; i<n; i++) {        par[i] = i;        rank[i] = 0;        opposite[i] = 0;    }}int find(int x) {    if(par[x] == x)        return x;    else        return par[x] = find(par[x]);}void unit(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]++;    }}bool same(int x, int y) {    return find(x) == find(y);}void solve(char c, int x, int y) {    if(c == 'D') {        if(opposite[x]==0 && opposite[y]==0) {            opposite[x] = y;            opposite[y] = x;        } else if(opposite[x] == 0) {            opposite[x] = y;            unit(x, opposite[y]);        } else if(opposite[y] == 0) {            opposite[y] = x;            unit(y, opposite[x]);        } else {            unit(x, opposite[y]);            unit(y, opposite[x]);        }    } else if(c == 'A') {        if(same(x, y))            printf("In the same gang.\n");        else if(same(x, opposite[y]))            printf("In different gangs.\n");        else            printf("Not sure yet.\n");    }}int main() {    freopen("in.txt", "r", stdin);    scanf("%d", &t);    while(t--) {        scanf("%d%d", &n, &m);        init(n * 2);//要开2*n的大小         char c[2];        int a, b;        while(m--) {            scanf("%s%d%d", &c, &a, &b);            solve(c[0], a, b);        }    }    fclose(stdin);    return 0;}
0 0
原创粉丝点击