HDU-2545(树的深度,并查集find()函数的应用)

点击打开题目链接

Input
输入包含多组数据
每组第一行包含两个数N,M(N,M<=100000),N表示树的节点数,M表示询问数,N=M=0表示输入结束。节点的编号为1到N。
接下来N-1行,每行2个整数A,B(1<=A,B<=N),表示编号为A的节点是编号为B的节点的父亲
接下来M行,每行有2个数,表示lxh和pfz的初始位置的编号X,Y(1<=X,Y<=N,X!=Y),lxh总是先移动

Output
对于每次询问,输出一行,输出获胜者的名字
 
Sample Input
 
  
2 1 1 2 1 2 5 2 1 2 1 3 3 4 3 5 4 2 4 5 0 0
Sample Output
 
 
lxh pfz lxh

分析:

找到每次两个节点离根节点的深度,

这里可以“借”用并查集中的find()函数来求深度

没有超时、

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>

using namespace std;

const int MAXN = 100005;
int T[MAXN];

void get_tree(int n);
int find_depth(int x);

int main()
{
    int m, n;
    while (cin >> n >> m && (n != 0 || m != 0))
    {
        memset(T, 0, sizeof(T)); // 必须要初始化,不然内存会超....!!!????

        get_tree(n - 1);
        for (int i = 0; i < m; i++)
        {
            int x, y;
            scanf("%d %d",&x,&y);
            int x1 = find_depth(x);
            int y1 = find_depth(y);
            if (x1 <= y1)
                printf("lxh\n");
            else
                 printf("pfz\n");
        }
    }
    return 0;
}

void get_tree(int n)
{
    int f, s;
    T[1] = 1;
    for (int i = 0; i < n; i++)
    {
        scanf("%d %d",&f,&s);
        T[s] = f;
    }
}

int find_depth(int x)
{
    int d = 0;
    while (x != T[x]) //当x不是根节点的时候,用递归,循环都可以
    {
         d = find_depth(T[x])+1;
         return d;
         //x=T[x];
        // d ++;
 }
    return d;
}

猜你喜欢

转载自blog.csdn.net/qq_41003528/article/details/80458558