zoukankan      html  css  js  c++  java
  • hdu 2545(并查集求节点到根节点的距离)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2545

    思路:dist[u]表示节点u到根节点的距离,然后在查找的时候更新即可,最后判断dist[u],dist[v]的大小即可。

     1 #include<iostream>
     2 #include<cstdio>
     3 #include<cstring>
     4 #include<algorithm>
     5 #include<vector>
     6 using namespace std;
     7 #define MAXN 101000
     8 
     9 int n,m;
    10 int parent[MAXN];
    11 int dist[MAXN];
    12 
    13 int Find(int x)
    14 {
    15     if(x==parent[x]){
    16         return parent[x];
    17     }
    18     int tmp=parent[x];
    19     parent[x]=Find(parent[x]);
    20     dist[x]+=dist[tmp];//更新到根节点的距离
    21     return parent[x];
    22 }
    23 
    24 int main()
    25 {
    26     int u,v;
    27     while(~scanf("%d%d",&n,&m)){
    28         if(n==0&&m==0)break;
    29         for(int i=1;i<=n;i++){
    30             parent[i]=i;
    31             dist[i]=0;
    32         }
    33         for(int i=1;i<n;i++){
    34             scanf("%d%d",&u,&v);
    35             parent[v]=u;
    36             dist[v]=1;
    37         }
    38         while(m--){
    39             scanf("%d%d",&u,&v);
    40             Find(u);
    41             Find(v);
    42             if(dist[u]<=dist[v]){
    43                 puts("lxh");
    44             }else 
    45                 puts("pfz");
    46         }
    47     }
    48     return 0;
    49 }
    View Code
  • 相关阅读:
    优化eclipse
    Servlet与jsp间的传值问题
    servlet & javabean
    Java数据类型
    CentOS 7 安装tomcat
    Nginx配置详解
    PHP文件缓存实现
    lnmp编译安装
    Php安全规范
    php编码规范
  • 原文地址:https://www.cnblogs.com/wally/p/3332725.html
Copyright © 2011-2022 走看看