USACO08OCT 牧场散步Pasture Walking

题面传送门我太懒了所以吃掉题面

可以发现如果两点不在一条链上的话,那么他们的最短路径一定会经过他们的\(LCA\)

所以可以维护一下每个点到树根的距离,然后大力前缀和乱搞就好了。

#include <bits/stdc++.h>

const int max_n=1e4+5;

int N,M,cnt;
int depth[max_n],father[15][max_n],lg2[max_n],first_edge[max_n],dis[max_n];

struct edge
{
    int to,w,next_edge;
}linker[max_n<<1];

inline int read()
{
    register int x=0;
    register char ch=getchar();
    while(!isdigit(ch))
        ch=getchar();
    while(isdigit(ch))
    {
        x=(x<<1)+(x<<3)+ch-'0';
        ch=getchar();
    }   
    return x;
} 

inline void add_edge(int x,int y,int z)
{
    linker[++cnt].to=y;
    linker[cnt].w=z;
    linker[cnt].next_edge=first_edge[x];
    first_edge[x]=cnt;
    return;
}

inline void LCA_init(int cur,int fa)
{
    depth[cur]=depth[fa]+1;
    father[0][cur]=fa;
    for(register int i=1;i<=lg2[depth[cur]];++i)
        father[i][cur]=father[i-1][father[i-1][cur]];
    for(register int k=first_edge[cur];k;k=linker[k].next_edge)
    {
        if(!depth[linker[k].to]) 
        {
            dis[linker[k].to]=dis[cur]+linker[k].w;
            LCA_init(linker[k].to,cur);
        }
    }
    return;
}

inline int LCA(int x,int y)
{
    if(depth[x]<depth[y]) std::swap(x,y);
    while(depth[x]>depth[y])
        x=father[lg2[depth[x]-depth[y]]][x];
    if(x==y) return x;
    for(register int i=lg2[depth[x]];i>=0;--i)
        if(father[i][x]!=father[i][y]) x=father[i][x],y=father[i][y];
    return father[0][x];
}

int main()
{
    int x,y,z;
    N=read(),M=read();
    lg2[0]=-1;
    for(register int i=1;i<N;++i)
    {
        x=read(),y=read(),z=read();
        add_edge(x,y,z),add_edge(y,x,z);
        lg2[i]=lg2[i>>1]+1;
    }
    lg2[N]=lg2[N>>1]+1;
    LCA_init(1,0);
    for(register int i=1;i<=M;++i)
    {
        x=read(),y=read();
        printf("%d\n",dis[x]+dis[y]-(dis[LCA(x,y)]<<1));
    }
    return 0;
}

转载于:https://www.cnblogs.com/zcdhj/p/8166819.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值