Tree chain problem
Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Problem Description
Coco has a tree, whose vertices are conveniently labeled by 1,2,…,n.
There are m chain on the tree, Each chain has a certain weight. Coco would like to pick out some chains any two of which do not share common vertices.
Find out the maximum sum of the weight Coco can pick
Input
The input consists of several test cases. The first line of input gives the number of test cases T (T<=10).
For each tests:
First line two positive integers n, m.(1<=n,m<=100000)
The following (n - 1) lines contain 2 integers ai bi denoting an edge between vertices ai and bi (1≤ai,bi≤n),
Next m lines each three numbers u, v and val(1≤u,v≤n,0
Output
For each tests:
A single integer, the maximum number of paths.
Sample Input
1 7 3 1 2 1 3 2 4 2 5 3 6 3 7 2 3 4 4 5 3 6 7 3
Sample Output
6
Hint
Stack expansion program: #pragma comment(linker, "/STACK:1024000000,1024000000")
dp[i]表示以i为根的子树的最优解。
sum[i]表示i的子节点的dp值之和。
dp[i] = max(sum[i] , w[p]+ sum[j] - dp[j] );p为以i为LCA的链,j为这条链上的节点。
(求sum和时包括链上每一个节点,减dp和时不需要减去dp[i])
在跑DFS时记录到达这个节点和离开这个节点时的ID,以这些ID为基础进行树状数组的维护,维护sum[]数组与dp[]数组。
当求某一条链上的sum[]和与dp[]和时,getsum(tid[u])+getsum[tid[v]]即可,tid[为]DFS的正序。
LCA使用的是在线倍增算法。
#pragma comment(linker, "/STACK:1024000000,1024000000")
#include
#include