http://acm.hdu.edu.cn/showproblem.php?pid=3966
题意:有n个点n-1条边,每个点有一个权值,有两种操作:询问一个点上权值是多少和修改u到v这条链上的权值。
思路:树链剖分。学习地址:http://blog.sina.com.cn/s/blog_7a1746820100wp67.html http://blog.csdn.net/acdreamers/article/details/10591443
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <algorithm>
#include <string>
#include <iostream>
#include <stack>
#include <map>
#include <queue>
using namespace std;
#define N 50010
#define INF 0x3f3f3f3f
#define lson rt<<1, l, m
#define rson rt<<1|1, m+1, r
struct node
{
int u, v, next;
}edge[N*];
int tot, head[N]; //存边部分
int tim, son[N], tid[N], fa[N], depth[N], size[N], top[N], num[N], rak[N]; //树剖部分
//分别对应DFS的时间、重儿子、节点的时间戳、父节点、节点深度、该节点的子树的节点数、树链中的头节点、初始节点权值、rak[i]表示时间戳为i的节点是rak[i](在线段树中的位置)
int tree[N<<], col[N<<]; //线段树部分
int n; void init()
{
tim = tot = ;
memset(head, -, sizeof(head));
memset(son, -, sizeof(son));
} void add(int u, int v)
{
edge[tot].next = head[u]; edge[tot].u = u; edge[tot].v = v; head[u] = tot++;
} void dfs1(int u, int f, int d)
{
size[u] = ;
depth[u] = d;
fa[u] = f;
for(int i = head[u]; ~i; i = edge[i].next) {
int v = edge[i].v;
if(f == v) continue;
dfs1(v, u, d + );
if(size[v] > size[son[u]] || son[u] == -) son[u] = v;
size[u] += size[v];
}
} void dfs2(int u, int f)
{
top[u] = f;
tid[u] = ++tim;
rak[tid[u]] = u;
if(son[u] == -) return ;
dfs2(son[u], f); //是重儿子的话
for(int i = head[u]; ~i; i = edge[i].next) {
int v = edge[i].v;
if(v != son[u] && v != fa[u]) dfs2(v, v); //不是重儿子的话
}
} void PushDown(int rt, int len)
{
if(col[rt]) {
col[rt<<] += col[rt];
col[rt<<|] += col[rt];
tree[rt<<] += (len - (len >> )) * col[rt];
tree[rt<<|] += (len >> ) * col[rt];
col[rt] = ;
}
} void Build(int rt, int l, int r)
{
col[rt] = ;
tree[rt] = ;
if(l == r) {
tree[rt] = num[rak[l]];
return ;
}
int m = (l + r) >> ;
Build(lson);
Build(rson);
} void Update(int rt, int l, int r, int L, int R, int val)
{
if(L <= l && r <= R) {
col[rt] += val;
tree[rt] += val * (r - l + );
return ;
}
PushDown(rt, r - l + );
int m = (l + r) >> ;
if(L <= m) Update(lson, L, R, val);
if(R > m) Update(rson, L, R, val);
} int Query(int rt, int l, int r, int id)
{
if(l == r && l == id) return tree[rt];
PushDown(rt, r - l + );
int m = (l + r) >> ;
if(id <= m) return Query(lson, id);
else return Query(rson, id);
} void Change(int u, int v, int val)
{
while(top[u] != top[v]) {
if(depth[top[u]] < depth[top[v]]) swap(u, v);
Update(, , n, tid[top[u]], tid[u], val); //父节点编号小
u = fa[top[u]]; //!!!
}
if(depth[u] > depth[v]) swap(u, v);
Update(, , n, tid[u], tid[v], val);
} int main()
{
int m, q, id, u, v, val;
char s[];
while(~scanf("%d%d%d", &n, &m, &q)) {
init();
for(int i = ; i <= n; i++) scanf("%d", &num[i]);
for(int i = ; i < m; i++) {
scanf("%d%d", &u, &v);
add(u, v); add(v, u);
}
dfs1(, -, );
dfs2(, );
Build(, , n);
while(q--) {
scanf("%s", s);
if(s[] == 'Q') {
scanf("%d", &id);
printf("%d\n", Query(, , n, tid[id]));
} else {
scanf("%d%d%d", &u, &v, &val);
if(s[] == 'D') val = -val;
Change(u, v, val);
}
}
}
return ;
}