LCA模板

#include <iostream>
#include <string.h>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <algorithm>
using namespace std;
#define ll long long
#define INF 0x3f3f3f3f
#define maxn 40005
struct Edge {
    int v, nxt, w;
}edge[maxn << 1];

int tot, head[maxn];
int dis[maxn], grand[maxn][30], fa[maxn], gx[maxn][30];
int n, m, ans;

void init() {
    tot = 0;
    memset(head, -1, sizeof(head));
    memset(grand, 0, sizeof(grand));
    memset(gx, 0, sizeof(gx));
    for (int i = 0; i < maxn; i++)
        fa[i] = i;
}

void addEdge(int u, int v, int w) {
    edge[tot].v = v;
    edge[tot].nxt = head[u];
    edge[tot].w = w;
    head[u] = tot++;

    edge[tot].v = u;
    edge[tot].nxt = head[v];
    edge[tot].w = w;
    head[v] = tot++;
}

void bfs(int root) {
    queue<int> que;
    memset(dis, -1, sizeof(dis));
    dis[root] = 1;
    que.push(root);
    while (!que.empty()) {
        int u = que.front(); que.pop();
        for (int i = head[u]; i + 1; i = edge[i].nxt) {
            int son = edge[i].v;
            if (dis[son] == -1) {
                dis[son] = dis[u] + 1;
                grand[son][0] = u;
                gx[son][0] = edge[i].w;
                que.push(son);
                for (int j = 1; (1 << j) <= n; j++) {
                    grand[son][j] = grand[grand[son][j - 1]][j - 1];
                    gx[son][j] = gx[son][j - 1] + gx[grand[son][j - 1]][j - 1];
                }
            }
        }
    }
}

int LCA(int a, int b) {
    if (dis[a] < dis[b]) swap(a, b);
    int dd = dis[a] - dis[b];
    for (int i = 0; (dd >> i); i++)
        if ((dd >> i) & 1) {
            ans += gx[a][i];
            a = grand[a][i];
        }

    for (int i = log2(n) + 1; i >= 0; i--)
        if (grand[a][i] != grand[b][i]) {
            ans += gx[a][i];
            ans += gx[b][i];
            a = grand[a][i];
            b = grand[b][i];
        }
    if (a == b) return ans;//return a
    ans += gx[a][0];
    ans += gx[b][0];
    return ans;//return a 表示最近公共祖先
}

int main(int argc, const char* argv[]) {
    int T;
    scanf("%d", &T);
    while (T--) {
        init();
        scanf("%d",&n);
        for (int i = 1; i <= n; i++) {
            int u, v, w;
            scanf("%d %d %d", &u, &v, &w);
            addEdge(u, v, w);
        }
        bfs(1);
        scanf("%d", &m);
        while (m--) {
            int a, b;
            ans = 0;
            scanf("%d %d", &a, &b);
            printf("%d
", LCA(a, b));
        }
    }


    return 0;
}
原文地址:https://www.cnblogs.com/ch-hui/p/12623866.html