bzoj1787 [Ahoi2008]Meet 紧急集合

本文介绍了一个针对三人路径查询的问题,并提出了一种优化解决方案。通过枚举和比较两个公共祖先节点来快速确定第三人的位置,从而减少了计算复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

如果只有两个人,就当然是水题了,只要找出lca就可以了。
那么,三个人呢。其实原理上应该是差不多的,先两两找出lca,得到三个lca,感性的认识一下,答案一定在这三个点之间,枚举一下就好了。

其实,还可以优化一下,我们可以发现,三个lca,一定有两个是相同的,那么,答案就是另一个。

#include<bits/stdc++.h>
#define N 500000
using namespace std;
vector <int> edge[N+1];
int n,m,x,y,z,ans,tmp1,tmp2,tmp3,id;
int father[N+1][20],dep[N+1];
inline char nc()
{
    char static buf[100000],*p1=buf,*p2=buf;
    return p1==p2&&(p2=(p1=buf)+fread(buf,1,100000,stdin),p1==p2)?EOF:*p1++;
}
inline int read()
{
    int x=0;
    char c=nc();
    while(c<'0'||c>'9')c=nc();
    while(c<='9'&&c>='0')x=x*10+c-'0',c=nc();
    return x;
}
inline void add(int x,int y)
{
    edge[x].push_back(y);
}
inline void DFS(int x,int fa)
{
    dep[x]=dep[fa]+1;
    father[x][0]=fa;
    for(int i=0;i<edge[x].size();i++)
    {
        int u=edge[x][i];
        if(u==fa)continue;
        DFS(u,x);
    }
}
inline int lca(int x,int y)
{
    if(dep[x]<dep[y])swap(x,y);
    int feet=dep[x]-dep[y];
    for(int i=19;i>=0;i--)
        if(feet>=(1<<i))x=father[x][i],feet-=(1<<i);
    if(x==y)return x;
    for(int i=19;i>=0;i--)
        if(father[x][i]!=father[y][i])
        {
            x=father[x][i];
            y=father[y][i];
        }
    return father[x][0];
}
inline int dis(int tmp)
{
    int ans=0,fa;
    fa=lca(tmp,x);
    ans+=dep[x]+dep[tmp]-2*dep[fa];
    fa=lca(tmp,y);
    ans+=dep[y]+dep[tmp]-2*dep[fa];
    fa=lca(tmp,z);
    ans+=dep[z]+dep[tmp]-2*dep[fa];
    return ans;
}
int main()
{
    //freopen("in.txt","r",stdin);
    n=read(),m=read();
    for(int i=1;i<n;i++)
    {
        x=read(),y=read();
        add(x,y),add(y,x);
    }
    DFS(1,0);
    for(int i=1;i<=19;i++)
        for(int j=1;j<=n;j++)
            father[j][i]=father[father[j][i-1]][i-1];
    for(int i=1;i<=m;i++)
    {
        x=read(),y=read(),z=read();
        tmp1=lca(x,y);
        tmp2=lca(y,z);
        tmp3=lca(z,x);
        if(tmp1==tmp2)ans=tmp3;
        else if(tmp1==tmp3)ans=tmp2;
        else if(tmp2==tmp3)ans=tmp1;
        printf("%d %d\n",ans,dis(ans));
    }
    return 0;
} 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值