poj 1703

本文介绍了一种使用并查集处理人物间对立关系的数据结构方法。通过维护一个对立数组或扩大并查集规模来记录对立关系,实现了对人物间是否属于同一阵营或对立阵营的快速判断。

并查集。
用一个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;
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值