URAL_1471
这个题目可以用树链剖分做,另外推荐一个讲树链剖分通俗易懂的博客:http://blog.sina.com.cn/s/blog_6974c8b20100zc61.html。
#include<stdio.h> #include<string.h> #define MAXD 50010 #define MAXM 100010 int N, Q, first[MAXD], next[MAXM], v[MAXM], e; int fa[MAXD], dep[MAXD], son[MAXD], size[MAXD], w[MAXD], top[MAXD], cnt; int q[MAXD], sum[4 * MAXD]; struct Edge { int x, y, z; }edge[MAXD]; void Swap(int &x, int &y) { int t; t = x, x = y, y = t; } void add(int x, int y) { v[e] = y; next[e] = first[x], first[x] = e ++; } void update(int cur) { sum[cur] = sum[cur << 1] + sum[cur << 1 | 1]; } void prepare() { int i, j, x, rear = 0; fa[1] = 0, dep[1] = 1; q[rear ++] = 1; for(i = 0; i < rear; i ++) { x = q[i]; for(j = first[x]; j != -1; j = next[j]) if(v[j] != fa[x]) { fa[v[j]] = x, dep[v[j]] = dep[x] + 1; q[rear ++] = v[j]; } } size[0] = 0; for(i = rear - 1; i >= 0; i --) { x = q[i]; size[x] = 1, son[x] = 0; for(j = first[x]; j != -1; j = next[j]) if(v[j] != fa[x]) { size[x] += size[v[j]]; if(size[v[j]] > size[son[x]]) son[x] = v[j]; } } cnt = 0; memset(top, 0, sizeof(top)); for(i = 0; i < rear; i ++) { x = q[i]; if(top[x] == 0) { for(j = x; j != 0; j = son[j]) top[j] = x, w[j] = ++ cnt; } } } void refresh(int cur, int x, int y, int k, int v) { int mid = (x + y) >> 1, ls = cur << 1, rs = cur << 1 | 1; if(x == y) { sum[cur] = v; return ; } if(k <= mid) refresh(ls, x, mid, k, v); else refresh(rs, mid + 1, y, k, v); update(cur); } void init() { int i, x, y, z; e = 0; memset(first, -1, sizeof(first)); for(i = 1; i < N; i ++) { scanf("%d%d%d", &x, &y, &z); ++ x, ++ y; edge[i].x = x, edge[i].y = y, edge[i].z = z; add(x, y), add(y, x); } prepare(); memset(sum, 0, sizeof(sum)); for(i = 1; i < N; i ++) { if(dep[edge[i].x] > dep[edge[i].y]) Swap(edge[i].x, edge[i].y); refresh(1, 1, N, w[edge[i].y], edge[i].z); } } void Search(int cur, int x, int y, int s, int t, int &ans) { int mid = (x + y) >> 1, ls = cur << 1, rs = cur << 1 | 1; if(x >= s && y <= t) { ans += sum[cur]; return ; } if(mid >= s) Search(ls, x, mid, s, t, ans); if(mid + 1 <= t) Search(rs, mid + 1, y, s, t, ans); } void deal(int x, int y) { int fx = top[x], fy = top[y], ans = 0; while(fx != fy) { if(dep[fx] > dep[fy]) Swap(fx, fy), Swap(x, y); Search(1, 1, N, w[fy], w[y], ans); y = fa[fy], fy = top[y]; } if(x != y) { if(dep[x] > dep[y]) Swap(x, y); Search(1, 1, N, w[son[x]], w[y], ans); } printf("%d\n", ans); } void solve() { int i, q, x, y; scanf("%d", &q); for(i = 0; i < q; i ++) { scanf("%d%d", &x, &y); deal(x + 1, y + 1); } } int main() { while(scanf("%d", &N) == 1) { init(); solve(); } return 0; }