HDU2545 树上战争

问题链接:HDU2545 树上战争

问题简述:参见上述链接。

问题分析:这是一个有关树的问题,可以构造一颗树来解决,类似于并查集中。哪个结点离树根更近则胜出。

程序说明:程序中,构建一个类似于并查集的树类,不过各个方法的逻辑已经不一样了。

AC的C++语言程序如下:

/* HDU2545 树上战争 */

#include <iostream>

using namespace std;

const int MAXN = 100000;

// 树类:并查集类的变种
int v[MAXN+1];
class uftree {
private:
    int length;
public:
    uftree(int n) {
        length = n;
        for(int i=0; i<=n; i++)
            v[i] = i;
    }

    inline void Union(int x, int y) {
        v[y] = x;
    }

    inline int getdistance(int x) {
        int ans = 0;
        while(x != v[x]) {
            x = v[x];
            ans++;
        }
        return ans;
    }
};

int main()
{
    int n, m, a, b, distance1, distance2;

    while(scanf("%d%d",&n,&m) != EOF && (n || m)) {
        uftree uft(n);

        for(int i=1; i<n; i++) {
            scanf("%d%d", &a, &b);

            uft.Union(a, b);
        }

        while(m--) {
            scanf("%d%d", &a, &b);

            distance1 = uft.getdistance(a);
            distance2 = uft.getdistance(b);

            if(distance1 <= distance2)
                printf("lxh
");
            else
                printf("pfz
");
        }
    }

    return 0;
}





原文地址:https://www.cnblogs.com/tigerisland/p/7564109.html