hdu 2586 How far away?(树链剖分+前缀和)
Posted jpphy0
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了hdu 2586 How far away?(树链剖分+前缀和)相关的知识,希望对你有一定的参考价值。
How far away?
http://acm.hdu.edu.cn/showproblem.php?pid=2586
分析
- 链式前向星
- 树链剖分、最近公共祖先(LCA)
- 根到叶子路径的前缀和
代码
// hdu 2586 How far away?
#include <bits/stdc++.h>
using namespace std;
#define MXN 40005
int h[MXN], fa[MXN], top[MXN], siz[MXN], d[MXN], son[MXN];
long long sum[MXN];
int n, m, cnt, ans;
struct Edge{int to = -1, nxt = -1, w;}e[MXN<<1];
void add(int u, int v, int w){
e[cnt].w = w;
e[cnt].to = v;
e[cnt].nxt = h[u];
h[u] = cnt++;
}
void dfs1(int x, int pre){
fa[x] = pre, d[x] = d[pre]+1;
siz[x] = 1, son[x] = 0;
for(int i = h[x]; ~i; i = e[i].nxt){// i != -1
int to = e[i].to;
if(to == pre) continue;
sum[to] = sum[x]+e[i].w;
dfs1(to, x);
siz[x] += siz[to];
if(siz[son[x]] < siz[to]) son[x] = to;
}
}
void dfs2(int x, int topx){
top[x] = topx;
if(son[x] == 0) return;
dfs2(son[x], topx);
for(int i = h[x]; ~i; i = e[i].nxt){
int to = e[i].to;
if(to == fa[x] || to == son[x]) continue;
dfs2(to, to);
}
}
int lca(int u, int v){
while(top[u] != top[v]){
// if(d[u] > d[v]) u = fa[top[u]]; // 错误,测试如下
/*
7 1
1 2 4
2 3 5
2 4 6
3 5 8
4 6 9
6 7 4
5 7
*/
if(d[top[u]] > d[top[v]]) u = fa[top[u]];
else v = fa[top[v]];
}
return d[u] > d[v] ? v : u;
}
int main() {
int u, v, w, t, tmp;
scanf("%d", &t);
while (t--) {
memset(h, -1, sizeof h);
cnt = 1;
scanf("%d%d", &n, &m);
for(int i = 1; i < n; ++i){
scanf("%d%d%d", &u, &v, &w);
add(u, v, w), add(v, u, w);
}
sum[1] = 0, d[0] = 0;
dfs1(1, 0), dfs2(1, 1);
while(m--){
scanf("%d%d", &u, &v);
tmp = lca(u, v);
printf("%lld\\n", sum[u]-sum[tmp]-sum[tmp]+sum[v]);
}
if(t!=0) printf("\\n");
}
return 0;
}
以上是关于hdu 2586 How far away?(树链剖分+前缀和)的主要内容,如果未能解决你的问题,请参考以下文章
HDU - 2586 How far away ?(暴力 | LCA)