zoukankan      html  css  js  c++  java
  • HDU2586 LCA

    题意:给定n个点,n-1条边,每两个点之间的路独一无二

    LCA

    View Code
     1 #include<stdio.h>
     2 #include<string.h>
     3 #include<stdlib.h>
     4 const int maxn = 40005;
     5 int head[ maxn ],cnt;
     6 struct node{
     7     int u,val,next;
     8 }edge[ maxn*2 ];
     9 int ace[ maxn ],fa[ maxn ],dis[ maxn ],deep[ maxn ];
    10 void init(){
    11     cnt=0;
    12     memset( head,-1,sizeof( head ));
    13     memset( fa,0,sizeof( fa ));
    14 }
    15 void addedge( int a,int b ,int c ){
    16     edge[ cnt ].u=b;
    17     edge[ cnt ].val=c;
    18     edge[ cnt ].next=head[ a ];
    19     head[ a ]=cnt++;
    20 }
    21 int n;
    22 
    23 void dfs( int now,int now_father,int now_deep,int now_dis,int now_ace ){
    24     fa[ now ]=now_father;
    25     deep[ now ]=now_deep;
    26     dis[ now ]=now_dis;
    27     deep[ now ]=now_deep;
    28     for( int i=head[ now ];i!=-1;i=edge[ i ].next ){
    29         int v=edge[ i ].u;
    30         if( fa[ v ]==0 )
    31             dfs( v,now,now_deep+1,now_dis+edge[ i ].val,now_ace );
    32     }
    33 }
    34 
    35 int find( int a,int b ){
    36     if( a==b )
    37         return a;
    38     if( deep[ a ]>deep[ b ] )
    39         return find( fa[ a ],b );
    40     else 
    41         return find( a,fa[ b ] );
    42 }
    43 
    44 int main(){
    45     int T;
    46     scanf("%d",&T);
    47     while( T-- ){
    48         init();
    49         int m;
    50         scanf("%d%d",&n,&m);
    51         int a,b,c;
    52         for( int i=0;i<n-1;i++ ){
    53             scanf("%d%d%d",&a,&b,&c);
    54             addedge( a,b,c );
    55             addedge( b,a,c );
    56         }
    57 
    58         for( int i=1;i<=n;i++ )
    59             if( fa[ i ]==0 )
    60                 dfs( i,-1,0,1,i );//x,fa[x],deep,dis,ace
    61 
    62         while( m-- ){
    63             scanf("%d%d",&a,&b);
    64             if( ace[ a ]==ace[ b ] ){
    65                 int k=find( a,b );
    66                 printf("%d\n",dis[a]+dis[b]-2*dis[k]);
    67             }
    68             else
    69                 printf("0\n");
    70         }
    71     //    printf("\n");
    72     }
    73     return 0;
    74 }
    keep moving...
  • 相关阅读:
    jquery中子元素和后代元素的区别
    MVC4 创建控制器时,无法检索元数据
    ref和out的用法说明举例(转)
    DataView的ToTable方法,类似数据库Distinct。
    oracle 19C 静默安装(单机版)
    Supervisord进程管家
    zabbix v3.0安装部署【转】
    Linux下Hadoop2.7.3集群环境的搭建
    Redis集群搭建与简单使用【转】
    redis+keepalived实现高可用
  • 原文地址:https://www.cnblogs.com/xxx0624/p/2893375.html
Copyright © 2011-2022 走看看