BZOJ 1602: [Usaco2008 Oct]牧场行走

1602: [Usaco2008 Oct]牧场行走

Time Limit: 5 Sec  Memory Limit: 64 MB
Submit: 2243  Solved: 1195
[Submit][Status][Discuss]

Description

N头牛(2<=n<=1000)别人被标记为1到n,在同样被标记1到n的n块土地上吃草,第i头牛在第i块牧场吃草。 这n块土地被n-1条边连接。 奶牛可以在边上行走,第i条边连接第Ai,Bi块牧场,第i条边的长度是Li(1<=Li<=10000)。 这些边被安排成任意两头奶牛都可以通过这些边到达的情况,所以说这是一棵树。 这些奶牛是非常喜欢交际的,经常会去互相访问,他们想让你去帮助他们计算Q(1<=q<=1000)对奶牛之间的距离。

Input

*第一行:两个被空格隔开的整数:N和Q

 *第二行到第n行:第i+1行有两个被空格隔开的整数:AI,BI,LI

*第n+1行到n+Q行:每一行有两个空格隔开的整数:P1,P2,表示两头奶牛的编号。

Output

*第1行到第Q行:每行输出一个数,表示那两头奶牛之间的距离。

Sample Input

4 2
2 1 2
4 3 2
1 4 3
1 2
3 2

Sample Output

2
7

思路:

  树链剖分, 对每个点求dis, 每次查询的ans = dis(a) +dis(b) - 2*dis(lca(a,b));

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
const int N =1100;
int head[N], to[N<<1], val[N<<1], nxt[N<<1], _;
int son[N], dep[N], top[N], fa[N],  siz[N];
int dis[N];
void add(int a, int b, int c) {
    to[++_] = b;
    nxt[_]  = head[a];
    head[a] = _;
    val[_] = c;

    to[++_] = a;
    nxt[_]  = head[b];
    head[b] = _;
    val[_] = c;
}
void dfs(int p) {
    dep[p] = dep[fa[p]] + 1;
    siz[p] = 1;
    for(int i=head[p];i;i=nxt[i]) {
        if(to[i]!=fa[p]) {
            fa[to[i]] = p;
            dis[to[i]] = dis[p] + val[i];
            dfs(to[i]);
            siz[p] += siz[to[i]];
            if(siz[to[i]] > siz[son[p]]) son[p] = to[i];
        }
    }
}
void dfs2(int p, int t) {
    top[p] = t;
    if(son[p]) dfs2(son[p], t);
    for(int i=head[p];i;i=nxt[i]) {
        if(to[i]!=fa[p]&&to[i]!=son[p]) {
            dfs2(to[i], to[i]);
        }
    }
}
int lca(int x, int y) {
    while(top[x]!=top[y]) {
        if(dep[top[x]]<dep[top[y]])swap(x, y);
        x=fa[top[x]];
    }
    return dep[x]>dep[y]?y:x;
}
int main() {
    int n, q;
    scanf("%d%d", &n, &q);
    for(int i=2;i<=n;i++) {
        int a, b, c;
        scanf("%d%d%d", &a, &b, &c);
        add(a, b, c);
    }

    dfs(1);
    dfs2(1, 1);
    /*for(int i = 1;i <= n; i++) {
        printf("%d
", dis[i]);
    }*/
    for(int i=1;i<=q;i++) {
        int a, b;
        scanf("%d%d", &a, &b);
        printf("%d
", dis[a]+dis[b]-2*dis[lca(a,b)]);
    }
}
View Code
原文地址:https://www.cnblogs.com/Tobichi/p/9204444.html