H. 3.小w的佛光(树上含公共点的两条路径的重合长度)


求重合长度的一个小trick:

Len:A->B与Len:B->C的共同路径长为
(Length(AB)+length(BC)-length(AC))/2
对于求length(AB):即其1+|dep[lca(a,b)]-dep[a]|+|dep[lca(a,b)]-dep[b]|
至于求lca,倍增树剖tarjan皆可
因为是点权,所以最后要+1
#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<cstdio>
#include<algorithm>
#define debug(a) cout<<#a<<"="<<a<<endl;
using namespace std;
const int maxn=3e5+100;
typedef long long LL;
inline LL read(){LL x=0,f=1;char ch=getchar();	while (!isdigit(ch)){if (ch=='-') f=-1;ch=getchar();}while (isdigit(ch)){x=x*10+ch-48;ch=getchar();}
return x*f;}
LL siz[maxn],fa[maxn],dep[maxn],son[maxn];
LL top[maxn];
vector<LL>g[maxn];
void predfs(LL u,LL father){
    siz[u]=1;
    dep[u]=dep[father]+1;
    fa[u]=father;
    for(LL i=0;i<g[u].size();i++){
        LL v=g[u][i];
        if(v==father) continue;
        predfs(v,u);
        siz[u]+=siz[v];
        if(siz[v]>siz[son[u]]) son[u]=v;
     }
}
void dfs(LL u,LL topx){
    top[u]=topx;
    if(son[u]==0) return;///叶子节点
    dfs(son[u],topx);///先处理重儿子
    for(LL i=0;i<g[u].size();i++){
        LL v=g[u][i];
        if(v==fa[u]||v==son[u]) continue;
        dfs(v,v);
    }
}
LL lca(LL u,LL v){
    while(top[u]!=top[v]){
        if(dep[top[u]]<dep[top[v]]){
            swap(u,v);
        }
        u=fa[top[u]];
    }
    return dep[u]<dep[v]?u:v;
}
int main(void)
{
  ///cin.tie(0);std::ios::sync_with_stdio(false);
  LL n,m,root,test;n=read();m=read();test=read();
  for(LL i=1;i<n;i++){
    LL u,v;u=read();v=read();
    g[u].push_back(v);g[v].push_back(u);
  }
  predfs(1,0);
  dfs(1,1);
  while(m--){
        LL A,B,C;A=read();B=read();C=read();
        LL s1=lca(A,B);LL s2=lca(C,B);LL s3=lca(A,C);
        LL len1=1+abs(dep[s1]-dep[A])+abs(dep[s1]-dep[B]);
        LL len2=1+abs(dep[s2]-dep[B])+abs(dep[s2]-dep[C]);
        LL len3=1+abs(dep[s3]-dep[A])+abs(dep[s3]-dep[C]);
        LL ans=(len1+len2-len3)/2+1;
        cout<<ans<<"\n";
  }
return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值