首页 > 代码库 > uva 12033 - Game of CS(树形删边)

uva 12033 - Game of CS(树形删边)

题目链接:uva 12033 - Game of CS

题目大意:给定图,以0为根节点,每条边有一个长度,两个人轮流操作,每次为一条边上色,上一个单位长度,当一条边的颜色被涂满,则算作是减掉整段子树。判断先手是否必胜。

解题思路:SG定理,对于当前节点u,每次考虑字节点v,u-v边的长度为l
当l为1时:sg(u) ^= (sg(v) + 1)
当l为奇数时: 需要判断sg(v)奇偶性,奇数-1,偶数+1;
当l为偶数时:sg(u) ^= sg(v)

#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>

using namespace std;
const int maxn = 1005;

int N, W[maxn][maxn];
vector<int> g[maxn];

int dfs (int u, int p) {
    int ret = 0;

    for (int i = 0; i < g[u].size(); i++) {
        int& v = g[u][i];
        if (v != p) {
            int sg = dfs(v, u);
            if (W[u][v] == 1)
                ret ^= (sg+1);
            else if (W[u][v]&1)
                ret ^= (sg + (sg&1 ? -1 : 1));
            else
                ret ^= sg;
        }
    }

    return ret;
}

int main () {
    int cas, u, v, w;
    scanf("%d", &cas);
    for (int k = 1; k <= cas; k++) {
        scanf("%d", &N);

        for (int i = 0; i < N; i++)
            g[i].clear();

        for (int i = 1; i < N; i++) {
            scanf("%d%d%d", &u, &v, &w);
            g[u].push_back(v);
            g[v].push_back(u);
            W[u][v] = W[v][u] = w;
        }

        printf("Case %d: %s\n", k, dfs(0, -1) ? "Emily" : "Jolly");
    }
    return 0;
}