树剖指针版lca之小机房的树

题目>>http://codevs.cn/problem/2370/
变量名及其他参照:http://blog.csdn.net/qq_36519085/article/details/77187441

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
const int MAXN = 4e5 + 5;
int n,m,firs[MAXN],nex[MAXN],cnt = 0,num = 0,a,b,c;
struct zt
{
    int f,t,v;
}road[MAXN];
struct zz
{
    int num,deep,dis,sz;
    zz *fa,*son,*top;
}tree[MAXN];
zz *fin[MAXN];
void build(int f,int t,int v)
{
    road[++cnt] = (zt){f,t,v};
    nex[cnt] = firs[f];
    firs[f] = cnt;
}
void build_tree(zz *root,int x,int f,int v)
{
    root->num = x;root->dis = v;fin[x] = root;
    root->deep = root->fa->deep + 1;
    root->sz = 1;
    for(int i = firs[x];i != -1;i = nex[i])
    {
        int u = road[i].t;
        if(u != f)
        {
            tree[++num].fa = root;
            build_tree(&tree[num],u,x,v + road[i].v);
            root->sz += fin[u]->sz;
            if(!root->son||root->son->sz < fin[u]->sz) root->son = fin[u];
        }
    }
}
void dfs(zz *root,zz *j)
{
    root->top = j;
    if(!root->son) return;
    if(root->son) dfs(root->son,j);
    for(int i = firs[root->num];i != -1;i = nex[i])
    {
        int v = road[i].t;
        if(v != root->son->num&&v != root->fa->num)
            dfs(fin[v],fin[v]);
    }
}
int lca(int a,int b)
{
    while(fin[a]->top != fin[b]->top)
    {
        if(fin[a]->top->deep > fin[b]->top->deep)
            a = fin[a]->top->fa->num;
        else b = fin[b]->top->fa->num;
    }
    return fin[a]->deep > fin[b]->deep ? b : a;
}
int main()
{
    scanf("%d",&n);
    for(int i = 0;i <= n;i ++) firs[i] = -1;
    for(int i = 1;i < n;i ++)
    {
        scanf("%d%d%d",&a,&b,&c);
        build(a,b,c);
        build(b,a,c);
    }//以上为基本建图 
    tree[0].fa = &tree[0];//确立根节点的父亲 
    build_tree(tree,0,0,0);
    dfs(tree,tree);
    scanf("%d",&m);
    for(int i = 1;i <= m;i ++)
    {
        scanf("%d%d",&a,&b);
        cout<<(fin[a]->dis + fin[b]->dis - (fin[lca(a,b)]->dis << 1))<<'\n';
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值