zoukankan      html  css  js  c++  java
  • codevs 1503 愚蠢的宠物

    题目描述 Description

    大家都知道,sheep有两只可爱的宠物(一只叫神牛,一只叫神菜)。有一天,sheep带着两只宠物到狗狗家时,这两只可爱的宠物竟然迷路了……

    狗狗的家因为常常遭到猫猫的攻击,所以不得不把家里前院的路修得非常复杂。狗狗家前院有N个连通的分叉结点,且只有N-1条路连接这N个节点,节点的编号是1-N(1为根节点)。sheep的宠物非常笨,他们只会向前走,不会退后(只向双亲节点走),sheep想知道他们最早什么时候会相遇(即步数最少)。

    输入描述 Input Description

    第1行:一个正整数N,表示节点个数。

    第2~N行:两个非负整数A和B,表示A是B的双亲。(保证A,B<=n)

    第N+1行:两个非负整数A和B,表示两只宠物所在节点的位置。(保证A,B<=n)

    输出描述 Output Description

    输出他们最早相遇的节点号。

    样例输入 Sample Input

    10
    1 2
    1 3
    1 4
    2 5
    2 6
    3 7
    4 8
    4 9
    4 10
    3 6

    样例输出 Sample Output

    1

    数据范围及提示 Data Size & Hint

    对于10%的数据,n<10^6

    对于100%的数据,n<=10^6

    思路:

    倍增求lca。

    代码:

    #include<cstdio>
    #include<iostream>
    #define maxn 1000001
    using namespace std;
    int n,tot,fa[maxn][25],head[maxn],deep[maxn];
    struct node
    {
        int to,next;
    }a[maxn*2];
    void add(int x,int y)
    {
        tot++;
        a[tot].to=y;
        a[tot].next=head[x];
        head[x]=tot;
    }
    void dfs(int x,int y,int d)
    {
        fa[x][0]=y;
        deep[x]=d;
        for(int i=head[x];i;i=a[i].next)
          if(y!=a[i].to)
            dfs(a[i].to,x,d+1);
    }
    int lca(int x,int y)
    {
        int i;
        if(deep[x]<deep[y])
          swap(x,y);
        int t=deep[x]-deep[y];
        for(i=0;i<=20;i++)
          if(t&(1<<i))
            x=fa[x][i];
        if(x==y)
          return x;
        for(i=20;i>=0;i--)
          if(fa[x][i]!=fa[y][i])
            x=fa[x][i],y=fa[y][i];
        return fa[x][0];
    }
    int main()
    {
        int i,j,x,y;
        scanf("%d",&n);
        for(i=1;i<n;i++)
          scanf("%d%d",&x,&y),add(x,y),add(y,x);
        dfs(1,1,0);
        for(j=1;j<=20;j++)
          for(i=1;i<=n;i++)
            fa[i][j]=fa[fa[i][j-1]][j-1];
        scanf("%d%d",&x,&y);
        printf("%d",lca(x,y));
        return 0;
    }
  • 相关阅读:
    html 上传图片前预览
    php获取当月天数及当月第一天及最后一天、上月第一天及最后一天实现方法
    php 计算 pdf文件页数
    php 获取半年内每个月的订单数量, 总价, 月份
    php 获取两个数组之间不同的值
    小程序支付功能
    关于nginx的Job for nginx.service failed because the control process exited with error code.错误
    linux 安装 Apollo
    MongoDB待续。。。
    ABP vNext...待续
  • 原文地址:https://www.cnblogs.com/jyhywh/p/6053078.html
Copyright © 2011-2022 走看看