zoj3195倍增lca

求三点之间的最短路,,分别求两点之间的lca除2即可(代码写的太挫了,wa了14发= =)

#include<map>
#include<set>
#include<cmath>
#include<queue>
#include<stack>
#include<vector>
#include<cstdio>
#include<cassert>
#include<iomanip>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
#define C 0.5772156649
#define pi acos(-1.0)
#define ll long long
#define mod 1000000007
#define ls l,m,rt<<1
#define rs m+1,r,rt<<1|1
#pragma comment(linker, "/STACK:1024000000,1024000000")

using namespace std;

const double g=10.0,eps=1e-7;
const int N=100000+10,maxn=500+100,inf=0x3f3f3f;

struct edge{
    int to,Next,w;
}e[N];
int head[N],dis[N];
int cnt,depth[N],father[20][N];
void add(int u,int v,int w)
{
    e[cnt].to=v;
    e[cnt].w=w;
    e[cnt].Next=head[u];
    head[u]=cnt++;
}
void dfs(int u,int f)
{
    father[0][u]=f;
    for(int i=head[u];~i;i=e[i].Next)
    {
        int To=e[i].to;
        if(To!=f)
        {
            depth[To]=depth[u]+1;
            dis[To]=dis[u]+e[i].w;
            dfs(To,u);
        }
    }
}
void init(int n)
{
    depth[1]=1;
    dis[1]=0;
    dfs(1,-1);
    for(int i=1;i<20;i++)
        for(int j=1;j<=n;j++)
           father[i][j]=father[i-1][father[i-1][j]];
}
int lca(int x,int y)
{
    if(depth[x]>depth[y])swap(x,y);
    for(int i=0;i<20;i++)
        if((depth[y]-depth[x])>>i&1)
           y=father[i][y];
    if(x==y)return x;
    for(int i=19;i>=0;i--)
    {
        if(father[i][x]!=father[i][y])
        {
            x=father[i][x];
            y=father[i][y];
        }
    }
    return father[0][x];
}
int getdis(int x,int y)
{
    return dis[x]+dis[y]-2*dis[lca(x,y)];
}
int main()
{
   /* ios::sync_with_stdio(false);
    cin.tie(0);*/
    int n,q=0;
    while(~scanf("%d",&n))
    {
        if(q)puts("");
        q=1;
        cnt=0;
        memset(head,-1,sizeof head);
        for(int i=1; i<n; i++)
        {
            int a,b,c;
            scanf("%d%d%d",&a,&b,&c);
            a++,b++;
            add(a,b,c);
            add(b,a,c);
        }
        init(n);
        int k;
        scanf("%d",&k);
        while(k--)
        {
            int a,b,c;
            scanf("%d%d%d",&a,&b,&c);
            a++,b++;c++;
            int ans=getdis(b,a)+getdis(c,b)+getdis(a,c);
            printf("%d
",ans/2);
        }
    }
    return 0;
}
/********************

********************/
View Code
原文地址:https://www.cnblogs.com/acjiumeng/p/7249619.html