codevs 2370 小機房的樹

      codevs 2370 小機房的樹spa

題目描述 Description

小機房有棵煥狗種的樹,樹上有N個節點,節點標號爲0到N-1,有兩隻蟲子名叫飄狗和大吉狗,分居在兩個不一樣的節點上。有一天,他們想爬到一個節點上去搞基,可是做爲兩隻蟲子,他們不想花費太多精力。已知從某個節點爬到其父親節點要花費 c 的能量(從父親節點爬到此節點也相同),他們想找出一條花費精力最短的路,以使得搞基的時候精力旺盛,他們找到你要你設計一個程序來找到這條路,要求你告訴他們最少須要花費多少精力設計

輸入描述 Input Description
第一行一個n,接下來n-1行每一行有三個整數u,v, c 。表示節點 u 爬到節點 v 須要花費 c 的精力。
第n+1行有一個整數m表示有m次詢問。接下來m行每一行有兩個整數 u ,v 表示兩隻蟲子所在的節點
輸出描述 Output Description

一共有m行,每一行一個整數,表示對於該次詢問所得出的最短距離。code

樣例輸入 Sample Input

3blog

1 0 1ip

2 0 1get

3string

1 0it

2 0io

1 2模板

樣例輸出 Sample Output

1

1

2

數據範圍及提示 Data Size & Hint

1<=n<=50000, 1<=m<=75000, 0<=c<=1000

思路:樹鏈剖分求LCA模板題

#include <algorithm>
#include <cstring>
#include <cstdio>
using namespace std;
const int M = 50005;
int n, m, tot;
int to[M*2], net[M*2], head[M], cap[M*2];
int deep[M], top[M], dad[M], size[M], length[M];

void add(int u, int v, int w) {
    to[++tot] = v; net[tot] = head[u]; head[u] = tot; cap[tot] = w;
    to[++tot] = u; net[tot] = head[v]; head[v] = tot; cap[tot] = w;
}

void dfs(int now) {
    size[now] = 1;
    deep[now] = deep[dad[now]] + 1;
    for (int i = head[now]; i; i = net[i])
        if (to[i] != dad[now]) {
            dad[to[i]] = now;
            length[to[i]] = length[now] + cap[i];
            dfs(to[i]);
            size[now] += size[to[i]];
        }
}

void dfsl(int now) {
    int t = 0;
    if (!top[now]) top[now] = now;
    for (int i = head[now]; i; i = net[i])
        if (to[i] != dad[now] && size[to[i]] > size[t])
            t = to[i];
    if (t) {
        top[t] = top[now];
        dfsl(t);
    }
    for (int i = head[now]; i; i = net[i])
        if (to[i] != dad[now] && to[i] != t)
            dfsl(to[i]);
}

int lca(int x, int y) {
    while (top[x] != top[y]) {
        if (deep[top[x]] < deep[top[y]])
            swap(x, y);
        x = dad[top[x]];
    }
    return deep[x] > deep[y] ? y : x;
}

int main() {
    scanf("%d", &n);
    for (int i = 1; i < n; ++i) {
        int u, v, w;
        scanf("%d%d%d", &u, &v, &w);
        add(u, v, w);
    }
    dfs(0); dfsl(0);
    scanf("%d", &m);
    for (int i = 1; i <= m; ++i) {
        int u, v;
        scanf("%d%d", &u, &v);
        int t = lca(u, v);
        printf("%d\n", length[u] + length[v] - length[t] * 2);
    }
    return 0;
}
相關文章
相關標籤/搜索