zoukankan      html  css  js  c++  java
  • SP14932 LCA

     1 #include<bits/stdc++.h>
     2 using namespace std;
     3 const int maxn=1005;
     4 const int maxm=3005;
     5 struct edge{int to,nex;}e[maxm];
     6 int head[maxn],tot;
     7 int deep[maxn],f[maxn][30];
     8 int T,n,m,q;
     9 inline void add(int x,int y){e[++tot].to=y;e[tot].nex=head[x];head[x]=tot;}
    10 void dfs(int k)
    11 {
    12     for(int i=head[k];i;i=e[i].nex)
    13     {
    14         if(!deep[e[i].to])
    15         {
    16             deep[e[i].to]=deep[k]+1;
    17             f[e[i].to][0]=k;
    18             dfs(e[i].to);
    19         }
    20     }
    21 }
    22 void init()
    23 {
    24     for(int j=1;(1<<j)<=n;++j)
    25         for(int i=1;i<=n;++i)
    26             if(f[i][j-1]) f[i][j]=f[f[i][j-1]][j-1];
    27 }
    28 int LCA(int x,int y)
    29 {
    30     if(deep[x]<deep[y]) swap(x,y);
    31     int i;for(i=0;(1<<i)<=n;++i);--i;
    32     for(int j=i;j>=0;--j) if(deep[x]-(1<<j)>=deep[y]) x=f[x][j];
    33     if(x==y) return x;
    34     for(int j=i;j>=0;--j) if(f[x][j]&&f[x][j]!=f[y][j]) x=f[x][j],y=f[y][j];
    35     return f[x][0];
    36 }
    37 void clear()
    38 {
    39     tot=0;
    40     memset(f,0,sizeof(f));
    41     memset(deep,0,sizeof(deep));
    42     memset(head,0,sizeof(head));
    43     memset(e,0,sizeof(e));
    44 }
    45 int main()
    46 {
    47     scanf("%d",&T);
    48     for(int i=1;i<=T;++i)
    49     {
    50         scanf("%d",&n);
    51         for(int j=1;j<=n;++j)
    52         {
    53             scanf("%d",&m);
    54             for(int k=1,tmp;k<=m;++k)
    55             {
    56                 scanf("%d",&tmp);
    57                 add(j,tmp);
    58             }
    59         }
    60         dfs(1);
    61         init();
    62         scanf("%d",&q);
    63         printf("Case %d:
    ",i);
    64         for(int i=1,x,y;i<=q;++i) scanf("%d%d",&x,&y),printf("%d
    ",LCA(x,y));
    65         clear();
    66     }
    67     return 0;
    68 }
  • 相关阅读:
    如何优雅地关闭资源
    JMeter使用教程2——MySQL压测
    JMeter使用教程
    Redis系列(五):消息队列
    Redis系列(四):地理信息
    Redis系列(三):Bitmaps和HyperLogLog
    Redis系列(二):常用操作
    Redis系列(一):安装
    linux命令学习_实验楼(总结)
    【转】Linux中常用的tar解压打包命令语法介绍
  • 原文地址:https://www.cnblogs.com/yu-xing/p/10262060.html
Copyright © 2011-2022 走看看