由于这个是一个有向图上的游戏,而且符合公平组合游戏的基本特征,所以可以直接求解各个节点的SG函数值。

#include<stdio.h>
#include<string.h>
#define MAXD 1010
#define MAXM 2010
int N, K, first[MAXD], next[MAXM], e, v[MAXM], sg[MAXD], h[MAXD][MAXD];
void add(int x, int y)
{
    v[e] = y;
    next[e] = first[x], first[x] = e ++;    
}
void dfs(int cur, int fa)
{
    int i;
    memset(h[cur], 0, sizeof(h[cur]));
    for(i = first[cur]; i != -1; i = next[i])
        if(v[i] != fa)    
        {
            dfs(v[i], cur);
            h[cur][sg[v[i]]] = 1;    
        }
    for(i = 0; h[cur][i]; i ++);
    sg[cur] = i;
}
void init()
{
    int i, j, k, x, y;
    memset(first, -1, sizeof(first));
    e = 0;
    for(i = 1; i < N; i ++)    
    {
        scanf("%d%d", &x, &y);
        add(x, y), add(y, x);
    }
}
void solve()
{
    int i, j, k;    
    dfs(K, -1);
    if(sg[K] == 0)
        printf("First player loses\n");
    else
    {
        k = N;
        for(i = first[K]; i != -1; i = next[i])    
        {
            if(sg[v[i]] == 0 && v[i] < k)
                k = v[i];
        }
        printf("First player wins flying to airport %d\n", k);
    }
}
int main()
{
    while(scanf("%d%d", &N, &K) == 2)
    {
        init();
        solve();    
    }
    return 0;    
}

 

posted on 2012-05-06 16:49  Staginner  阅读(255)  评论(0编辑  收藏  举报