ZOJ - 3195 -- Design the city

题目来源:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3195

给定一棵树,查询连通任意三点的路径的总长度。

设给定的三点为x,y,z。三点之间的路径总长度=(lca(x,y)+lca(y,z)+lca(x,z))/2。

代码:

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cstdlib>
#include <iostream>
#define ll long long
using namespace std;

const int maxn = 5e4 + 10;
const int maxh = 19;
int n, head[maxn], cnt, q, s[maxn], anc[maxn][maxh], lcs[maxn][maxh], dep[maxn];
struct edge {
    int to, next, vi;
} e[maxn * 2];

void ins(int x, int y, int z) {
    e[++cnt].to = y;
    e[cnt].next = head[x];
    e[cnt].vi = z;
    head[x] = cnt;
}

void build(int root) {
    int top = 0;
    s[++top] = root;
    dep[root] = 1;
    for (int i = 0; i < maxh; ++i) {
        anc[root][i] = root;
        lcs[root][i] = 0;
    }
    while (top) {
        int x = s[top--];
        if (x != root)
            for (int i = 1; i < maxh; ++i) {
                anc[x][i] = anc[anc[x][i - 1]][i - 1];
                lcs[x][i] = lcs[x][i - 1] + lcs[anc[x][i - 1]][i - 1];
            }
        for (int i = head[x]; i; i = e[i].next) {
            int y = e[i].to;
            if (y == anc[x][0])continue;
            dep[y] = dep[x] + 1;
            anc[y][0] = x;
            lcs[y][0] = e[i].vi;
            s[++top] = y;
        }
    }
}

int swim(int &x, int h) {
    int tot = 0;
    for (int i = 0; h > 0; ++i) {
        if (h & 1) {
            tot += lcs[x][i];
            x = anc[x][i];
        }
        h = (h>>1);
    }
    return tot;
}

int lca(int x, int y) {
    int tot = 0;
    if (dep[x] > dep[y])swap(x, y);
    tot += swim(y, dep[y] - dep[x]);
    if (x == y)return tot;
    while (1) {
        int pos;
        for (pos = 0; anc[x][pos] != anc[y][pos]; ++pos);
        if (pos == 0) {
            tot += lcs[x][0];
            tot += lcs[y][0];
            return tot;
        }
        tot += lcs[x][pos - 1];
        x = anc[x][pos - 1];
        tot += lcs[y][pos - 1];
        y = anc[y][pos - 1];
    }
}

int solve(int x,int y,int z) {
    return (lca(x, y) + lca(y, z) + lca(x, z)) / 2;
}

int main() {
    int _ = 0;
    while (~scanf("%d", &n)) {
        if (_)printf("\n");
        else _ = 1;
        int x, y, z;
        cnt = 0;
        memset(head, 0, sizeof(head));
        memset(dep, 0, sizeof(dep));
        memset(lcs, 0, sizeof(lcs));
        for (int i = 1; i < n; ++i) {
            scanf("%d%d%d", &x, &y, &z);
            ins(x, y, z);
            ins(y, x, z);
        }
        build(0);
        scanf("%d", &q);
        for (int i = 1; i <= q; ++i) {
            scanf("%d%d%d", &x, &y, &z);
            printf("%d\n", solve(x, y, z));
        }
    }
    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值