poj 2912(带权并查集)

题意:有n个人玩石头剪刀布的游戏,编号从1到n-1,把所有人分成3组,给每个组分配一个手势(石头、剪子、布),每轮挑出两个人出来进行游戏,这n个人里有一个裁判,他的手势是可以变化的。给出了m轮的游戏结果,a < b表示b赢了a,a = b表示a和b出了同样的手势,问能否找到裁判的编号,是在第几轮发现的。
题解:这题和食物链那个经典带权并查集很像,也可以用0表示父与子是同一种手势,用1表示父大于子,用2表示父小于子。因为裁判的编号不能确定,可以采用枚举的方式,先假定一个人是裁判,然后去掉这个人所有的比赛,根据是否发生矛盾,发生了几次矛盾,确定这个人是否是裁判,注意无论让哪个人当裁判都会出现矛盾,说明有两个裁判,输出Impossible。

#include <cstdio>
#include <cstring>
#include <map>
#include <algorithm>
using namespace std;
const int N = 505;
const int M = 2015;
int n, m, pa[N], rel[N];
int l[M], r[M];
char c, ch[M];
map<char, int> mp;

int get_parent(int x) {
    if (x != pa[x]) {
        int px = get_parent(pa[x]);
        rel[x] = (rel[x] + rel[pa[x]]) % 3;
        pa[x] = px;
    }
    return pa[x];
}

int main() {
    mp['='] = 0;
    mp['>'] = 1;
    mp['<'] = 2;
    while (scanf("%d%d", &n, &m) == 2) {
        for (int i = 0; i < m; i++) {
            scanf("%d", &l[i]);
            while (1) {
                c = getchar();
                if (c != ' ')
                    break;
            }
            ch[i] = c;
            scanf("%d", &r[i]);
        }
        int res = -1, res2 = 0, i;
        for (i = 0; i < n; i++) {
            int j;
            for (j = 0; j < n; j++) {
                pa[j] = j;
                rel[j] = 0;
            }
            for (j = 0; j < m; j++) {
                if (l[j] == i || r[j] == i)
                    continue;
                int px = get_parent(l[j]);
                int py = get_parent(r[j]);
                if (px == py) {
                    if (((rel[r[j]] - rel[l[j]] + 3) % 3) != mp[ch[j]]) {
                        res2 = max(j + 1, res2);
                        break;
                    }
                }
                else {
                    pa[py] = px;
                    rel[py] = (rel[l[j]] + mp[ch[j]] - rel[r[j]] + 3) % 3;
                }
            }
            if (j == m) {
                if (res != -1) {
                    printf("Can not determine\n");
                    break;
                }
                else
                    res = i;
            }
        }
        if (res == -1)
            printf("Impossible\n");
        if (res != -1 && i == n)
            printf("Player %d can be determined to be the judge after %d lines\n", res, res2);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值