Query on the subtree
Time Limit: 16000/8000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 384 Accepted Submission(s): 133
Problem Description
bobo has a tree, whose vertices are conveniently labeled by 1,2,…,n. At the very begining, the i-th vertex is assigned with weight w
i.
There are q operations. Each operations are of the following 2 types:
Change the weight of vertex v into x (denoted as "! v x"),
Ask the total weight of vertices whose distance are no more than d away from vertex v (denoted as "? v d").
Note that the distance between vertex u and v is the number of edges on the shortest path between them.
Input
The input consists of several tests. For each tests:
The first line contains n,q (1≤n,q≤10
5). The second line contains n integers w
1,w
2,…,w
n (0≤w
i≤10
4). Each of the following (n - 1) lines contain 2 integers a
i,b
i denoting an edge between vertices a
i and b
i (1≤a
i,b
i≤n). Each of the following q lines contain the operations (1≤v≤n,0≤x≤10
4,0≤d≤n).
Output
For each tests:
For each queries, a single number denotes the total weight.
Sample Input
4 3
1 1 1 1
1 2
2 3
3 4
? 2 1
! 1 0
? 2 1
3 3
1 2 3
1 2
1 3
? 1 0
? 1 1
? 1 2
Sample Output
题意:给了一棵带点权的树,支持两种操作! u w 将u的权值修改为w,? u d 询问与u的距离不超过d的点的权值和
思路:这道题拖了好久,AC以后还是很愉快的
树分治
对于每个分治中心center,用树状数组维护与它的距离为d的点权的和
然后要查询与点u距离不超过d的点权值和,可以通过分治中心center来查询
设u与center的距离为dis,则只需要统计与center距离为d-dis的点的权值和就好了,但是会将u所在的子树这部分算多余
所以还要减去u所在子树的这部分权值和,所以还需要用树状数组维护每个子树中的点与对应的分治中心center距离为d的点的权值和,以及这个子树所对应的分治中心
然后要查询的时候,只需要统计一遍u所在的所有子树以及对应的分治中心就可以了