树上战争 HDU-2545 【并查集】

来源:互联网 发布:淘宝店铺怎么发布微淘 编辑:程序博客网 时间:2024/05/17 02:53

题意:两个人A,B在树上的两个节点上,当一个人在一个节点的时候,节点的子树全都属于该者。 谁先占领了另一方的节点,那么该方胜利。

思路: 并查集。 谁离根节点近,谁就是胜利者

#include <bits/stdc++.h>using namespace std;typedef long long ll;int n,m;int par[100000+50];void init(){    for(int i=1; i<=n; i++)        par[i]=i;}int find(int root){    int cnt=0;    while(par[root]!=root)    {        root=par[root];        cnt++;    }    return cnt;}int main(void){    while(cin >> n >> m,n,m)    {        init();        for(int i=1; i<=n-1; i++)        {            int father,son;            scanf("%d%d",&father,&son);            par[son]=father;// 建树        }        for(int i=1; i<=m; i++)        {            int x,y;            scanf("%d%d",&x,&y);            if(find(x)<=find(y))// lxh先手所以有等号                printf("lxh\n");            else                printf("pfz\n");        }    }}
原创粉丝点击