UESTC 32 树上战争(Battle on the tree)

这题其实很简单,每个人肯定都往上走,才能保证尽快赢,所以无非是看谁离根节点近,即深度小。。用并查集中的findset思想,不断找父节点一直到根节点来找深度就可以了。

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
#define N 100007

int fa[N],n,cnt;

void init()
{
    for(int i=1;i<=n;i++)
        fa[i] = i;
}

void findset(int x)
{
    if(x != fa[x])
    {
        findset(fa[x]);
        cnt++;
    }
}

int main()
{
    int m,a,b,x,y,i;
    while(scanf("%d%d",&n,&m)!=EOF && (n||m))
    {
        init();
        for(i=0;i<n-1;i++)
        {
            scanf("%d%d",&a,&b);
            fa[b] = a;
        }
        while(m--)
        {
            scanf("%d%d",&x,&y);
            cnt = 0;
            findset(x);
            int kx = cnt;
            cnt = 0;
            findset(y);
            int ky = cnt;
            if(kx <= ky)
                puts("lxh");
            else
                puts("pfz");
        }
    }
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/whatbeg/p/3610681.html