FZU2082-过路费

来源:互联网 发布:lol竞猜软件 编辑:程序博客网 时间:2024/04/28 10:05

                                                Problem 2082 过路费

Accept: 801    Submit: 2505
Time Limit: 1000 mSec    Memory Limit : 32768 KB

 Problem 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 31 2 11 1 20 1 21 2 1

 Sample Output

12

 Source

FOJ有奖月赛-2012年4月(校赛热身赛)


解题思路:树链剖分,边权给点权即可



#include <iostream>#include <cstdio>#include <cstring>#include <string>#include <algorithm>#include <cmath>#include <map>#include <set>#include <stack>#include <queue>#include <vector>#include <bitset>#include <functional>using namespace std;#define LL long longconst int INF = 0x3f3f3f3f;int n, m, x, y, z;int s[100009], nt[100009], e[100009], v[100009], cnt;int ct[100009], mx[100009], fa[100009], dep[100009];int top[100009], g[100009], G[100009], a[100009];LL sum[100009];int lowbit(int x){return x&-x;}void add(int x, int y){while (x <= n){sum[x] += y;x += lowbit(x);}}LL getsum(int x){LL res = 0;while (x){res += sum[x];x -= lowbit(x);}return res;}void dfs(int x, int f){dep[x] = dep[f] + 1;fa[x] = f; ct[x] = 1; mx[x] = 0;for (int i = s[x]; ~i; i = nt[i]){if (e[i] == f) continue;dfs(e[i], x);ct[x] += ct[e[i]];if (ct[e[i]] > ct[mx[x]]) mx[x] = e[i];}}void Dfs(int x, int t){top[x] = !t ? x : top[fa[x]];g[x] = ++cnt;if (mx[x]) Dfs(mx[x], 1);for (int i = s[x]; ~i; i = nt[i]){if (e[i] == fa[x]) continue;if (e[i] == mx[x]) { G[v[i]] = g[e[i]]; continue; }Dfs(e[i], 0);G[v[i]] = g[e[i]];}}LL getans(int x, int y){LL ans = 0;while (top[x] != top[y]){if (dep[top[x]] < dep[top[y]]) swap(x, y);ans += getsum(g[x]) - getsum(g[top[x]] - 1); x = fa[top[x]];}if (dep[x] > dep[y]) swap(x, y);return ans + getsum(g[y]) - getsum(g[x]);}int main(){while (~scanf("%d%d", &n, &m)){memset(s, -1, sizeof s);memset(sum, 0, sizeof sum);dep[0] = ct[0] = cnt = 0;for (int i = 1; i < n; i++){scanf("%d%d%d", &x, &y, &a[i]);nt[cnt] = s[x], s[x] = cnt, v[cnt] = i, e[cnt++] = y;nt[cnt] = s[y], s[y] = cnt, v[cnt] = i, e[cnt++] = x;}dfs(1, 0);Dfs(1, cnt = 0);for (int i = 1; i < n; i++) add(G[i], a[i]);while (m--){scanf("%d%d%d", &x, &y, &z);if (!x){add(G[y], -a[y]);add(G[y], a[y] = z);}else printf("%lld\n", getans(y, z));}}return 0;}

原创粉丝点击