树链剖分后要处理的是边的权值,而不是点的权值,但是只要边权下放到点,就可以了
如图
但是问题是,求图4->5路径的权值之和, 那么就会把点3给算进去
那么就要减去,
或者干脆不加进去
有两种方法
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <algorithm>
#include <iostream>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <set>
#include <string>
#include <math.h>
using namespace std;
#pragma warning(disable:4996)
#pragma comment(linker, "/STACK:1024000000,1024000000")
typedef long long LL;
const int INF = <<;
/*
12 1
1 2 1
2 3 1
3 4 1
4 5 1
5 11 1
11 12 1
1 6 1
6 7 1
7 8 1
6 9 1
6 10 1
1 9 10
*/
const int N = + ;
vector<int> g[N];
int size[N], son[N], fa[N], depth[N], top[N], w[N], num, ra[N];
LL tree[N*];
int edge[N][];
int h[N];
void dfs(int u)
{
size[u] = ;
son[u] = ;
for (int i = ; i < g[u].size(); ++i)
{
int v = g[u][i];
if (v != fa[u])
{
fa[v] = u;
depth[v] = depth[u] + ;
dfs(v);
size[u] += size[v];
if (size[v] > size[son[u]])
son[u] = v;
}
}
} void dfs2(int u, int tp)
{
w[u] = ++num;
ra[num] = u;
top[u] = tp;
if (son[u] != )
dfs2(son[u], top[u]);
for (int i = ; i < g[u].size(); ++i)
{
int v = g[u][i];
if (v != fa[u] && v != son[u])
dfs2(v, v);
} }
void pushUp(int rt)
{
tree[rt] = tree[rt << ] + tree[rt << | ];
}
void update(int l, int r, int rt, int pos, int val)
{
if (l == r)
{
tree[rt] = val;
return;
}
int mid = (l + r) >> ;
if (pos <= mid)
update(l, mid, rt << , pos, val);
else
update(mid + , r, rt << | , pos, val);
pushUp(rt);
} LL ans;
void query(int l, int r, int rt, int L, int R)
{
if (L <= l&&R >= r)
{
ans += tree[rt];
return;
}
int mid = (l + r) >> ;
if (L <= mid)
query(l, mid, rt << , L, R);
if (R > mid)
query(mid + , r, rt << | , L, R);
}
int main()
{
int n, m, a, b, c;
while (scanf("%d%d", &n, &m) != EOF)
{
memset(tree, , sizeof(tree));
for (int i = ; i <= n; ++i)
g[i].clear();
num = ;
for (int i = ; i < n; ++i)
{
scanf("%d%d%d", &edge[i][], &edge[i][], &edge[i][]);
g[edge[i][]].push_back(edge[i][]);
g[edge[i][]].push_back(edge[i][]);
}
fa[] = depth[] = ;
dfs();
dfs2(, );
for (int i = ; i < n; ++i)
{
if (depth[edge[i][]] > depth[edge[i][]])
swap(edge[i][], edge[i][]);
h[edge[i][]] = edge[i][];
update(, n, , w[edge[i][]], edge[i][]);
}
while (m--)
{
scanf("%d%d%d", &a, &b, &c);
if (a == )
{
if (depth[edge[b][]] > depth[edge[b][]])
swap(edge[b][], edge[b][]);
update(, n, , w[edge[b][]], c);
h[edge[b][]] = c;
}
else
{
ans = ;
while (top[b] != top[c])
{
if (depth[top[b]] < depth[top[c]])
swap(b, c);
query(, n, , w[top[b]], w[b]);
b = fa[top[b]];
}
//b和c一定是在一条链上
if (depth[b]>depth[c])
swap(b, c); //如果b有父亲,那么就有边下放到它,多加了这个点,要减去
query(, n, , w[b], w[c]);
if (fa[b] != )
ans -= h[b];
/*
如果b,c是在一条重链上, 那么询问w[son[b]] 到w[c]
那么就没有加到点b
否则,b,c就是指向同一点,那么w[son[b]] > w[c] , 询问是不会增加任何值的
query(1, n, 1, w[son[b]], w[c]);
*/
printf("%lld\n", ans);
}
}
}
return ;
}