BZOJ 1787 [Ahoi2008]Meet 紧急集合 题解

Description:


Input


Output


Sample Input

6 4
1 2
2 3
2 4
4 5
5 6
4 5 6
6 3 1
2 4 4
6 6 6

Sample Output

5 2
2 5
4 1
6 0

HINT




/**************************************************************
    Problem: 1787
    User: 不告诉你!
    Language: C++
    Result: Accepted
    Time:3684 ms
    Memory:73556 kb
****************************************************************/
#include<iostream>
#include<cstdio>
using namespace std;
int n,m,cou;
int mem[500010],vis[500010],depth[500010],fa[500010][30];
struct node
{
    int to,next;
}edge[1000010];
void build(int u,int v)
{
    cou++;
    edge[cou].to=v;
    edge[cou].next=mem[u];
    mem[u]=cou;
}
void dfs(int x)
{
    vis[x]=1;
    for(int i=1;i<=18;i++)
    {
        if(depth[x]<(1<<i))
            break;
        fa[x][i]=fa[fa[x][i-1]][i-1];
    }
    for(int i=mem[x];i;i=edge[i].next)
    {
        if(vis[edge[i].to])
            continue;
        depth[edge[i].to]=depth[x]+1;
        fa[edge[i].to][0]=x;
        dfs(edge[i].to);
    }
}
int LCA(int x,int y)
{
    if(depth[x]<depth[y])
        swap(x,y);
    int dif=depth[x]-depth[y];
    for(int i=0;i<=18;i++)
        if(dif&(1<<i))
            x=fa[x][i];
    for(int i=18;i>=0;i--)
        if(fa[x][i]!=fa[y][i])
        {
                x=fa[x][i];
                y=fa[y][i];
        }
    if(x==y)
        return x;
    return fa[x][0];
}
void get_ans(int x,int y,int z)
{
    int t1,t2,t3;
    t1=LCA(x,y);t2=LCA(y,z);t3=LCA(x,z);
    int k1,k2,k3;
    k1=LCA(t1,z);k2=LCA(t2,x);k3=LCA(t3,y);
    int t,ans=233333333,dif;
    dif=depth[x]+depth[y]-depth[t1]+depth[z]-2*depth[k1];
    if(dif<ans)
    {
        ans=dif;t=t1;
    }
    dif=depth[y]+depth[z]-depth[t2]+depth[x]-2*depth[k2];
    if(dif<ans)
    {
        ans=dif;t=t2;
    }
    dif=depth[x]+depth[z]-depth[t3]+depth[y]-2*depth[k3];
    if(dif<ans)
    {
        ans=dif;t=t3;
    }
    printf("%d %d\n",t,ans);
    return;
}
int main()
{
    scanf("%d%d",&n,&m);
    int u,v;
    for(int i=1;i<n;i++)
    {
        scanf("%d%d",&u,&v);
        build(u,v);build(v,u);
    }
    dfs(1);
    for(int i=1;i<=m;i++)
    {
        int x,y,z;
        scanf("%d%d%d",&x,&y,&z);
        get_ans(x,y,z);
    }
    return 0;
}






  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值