题目:http://acm.fzu.edu.cn/problem.php?pid=2082
题意:Description
有n座城市,由n-1条路相连通,使得任意两座城市之间可达。每条路有过路费,要交过路费才能通过。每条路的过路费经常会更新,现问你,当前情况下,从城市a到城市b最少要花多少过路费。
Input
有多组样例,每组样例第一行输入两个正整数n,m(2 <= n<=50000,1<=m <= 50000),接下来n-1行,每行3个正整数a b c,(1 <= a,b <= n , a != b , 1 <= c <= 1000000000).数据保证给的路使得任意两座城市互相可达。接下来输入m行,表示m个操作,操作有两种:一. 0 a b,表示更新第a条路的过路费为b,1 <= a <= n-1 ; 二. 1 a b , 表示询问a到b最少要花多少过路费。
Output
对于每个询问,输出一行,表示最少要花的过路费。
Sample Input
2 3
1 2 1
1 1 2
0 1 2
1 2 1
Sample Output
1
2
思路:树链剖分,线段树维护区间和,入门题
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 30010;
struct edge
{
int to, next;
}g[N*2];
struct node
{
int l, r, val, sum;
}s[N*4];
int dep[N], siz[N], son[N], top[N], fat[N], id[N], head[N];
int d[N][3], val[N];
int n, cnt, num;
void add_edge(int v, int u)
{
g[cnt].to = u;
g[cnt].next = head[v];
head[v] = cnt++;
}
void dfs1(int v, int fa, int d)
{
dep[v] = d, fat[v] = fa, siz[v] = 1, son[v] = 0;
for(int i = head[v]; i != -1; i = g[i].next)
{
int u = g[i].to;
if(u != fa)
{
dfs1(u, v, d + 1);
siz[v] += siz[u];
if(siz[son[v]] < siz[u])
son[v] = u;
}
}
}
void dfs2(int v, int tp)
{
top[v] = tp, id[v] = ++num;
if(son[v]) dfs2(son[v], tp);
for(int i = head[v]; i != -1; i = g[i].next)
{
int u = g[i].to;
if(u != son[v] && u != fat[v])
dfs2(u, u);
}
}
void push_up(int k)
{
s[k].val = s[k<<1].val + s[k<<1|1].val;
}
void build(int l, int r, int k)
{
s[k].l = l, s[k].r = r;
if(l == r)
{
s[k].val = val[l];
return;
}
int mid = (l + r) >> 1;
build(l, mid, k << 1);
build(mid + 1, r, k << 1|1);
push_up(k);
}
void update(int v, int c, int k)
{
if(s[k].l == s[k].r)
{
s[k].val = c; return;
}
int mid = (s[k].l + s[k].r) >> 1;
if(v <= mid) update(v, c, k << 1);
else update(v, c, k << 1|1);
push_up(k);
}
int seek(int l, int r, int k)
{
if(l <= s[k].l && s[k].r <= r)
return s[k].val;
int mid = (s[k].l + s[k].r) >> 1, ans = 0;
if(l <= mid) ans += seek(l, r, k << 1);
if(r > mid) ans += seek(l, r, k << 1 | 1);
return ans;
}
int query(int v, int u)
{
int t1 = top[v], t2 = top[u], ans = 0;
while(t1 != t2)
{
if(dep[t1] < dep[t2])
swap(t1, t2), swap(v, u);
ans += seek(id[t1], id[v], 1);
v = fat[t1];
t1 = top[v];
}
if(v == u) return ans;
if(dep[v] > dep[u]) swap(v, u);
return ans + seek(id[son[v]], id[u], 1);
}
int main()
{
int m;
while(~scanf("%d%d", &n, &m))
{
memset(head, -1, sizeof head);
cnt = 0, num = 0;
for(int i = 1; i <= n - 1; i++)
{
scanf("%d%d%d", &d[i][0], &d[i][1], &d[i][2]);
add_edge(d[i][0], d[i][1]);
add_edge(d[i][1], d[i][0]);
}
dfs1(1, 0, 1);
dfs2(1, 1);
for(int i = 1; i <= n - 1; i++)
{
if(dep[d[i][0]] > dep[d[i][1]])
swap(d[i][0], d[i][1]);
val[id[d[i][1]]] = d[i][2];
}
build(1, num, 1);
int a, b, c;
for(int i = 0; i < m; i++)
{
scanf("%d%d%d", &a, &b, &c);
if(a == 0) update(id[d[b][1]], c, 1);
else printf("%d\n", query(b, c));
}
}
return 0;
}