Masha and Cactus
Time limit4sMemory limit512 MB
Choose a maximum-weight subset of extra edges whose tree paths keep each vertex in at most one cycle, by a subtree DP with lazy updates on the path to the root.
- Level
Hard8 of 10
- Topics
- Tree, Dynamic programming, Greedy, Segment tree
- Solved
- No attempts yet
Problem
Masha is fond of cacti. When she was a little girl, she decided to plant a tree. Now Masha wants to make a nice cactus out of her tree.
A tree is a connected undirected graph that has no cycles. A cactus is a connected undirected graph in which each vertex belongs to at most one cycle.
Masha has some additional edges that she can add to the tree. For each edge she knows which vertices it would connect and the beauty of this edge. Masha can add some of these edges to the graph if the resulting graph is a cactus. The beauty of the resulting cactus is the sum of the beauties of all added edges.
Help Masha find out what maximum beauty of the resulting cactus she can achieve.
Input
The first line of the input contains two integers n and m: the number of vertices in the tree, and the number of additional edges available (3 ≤ n ≤ 2·10^5; 0 ≤ m ≤ 2·10^5).
Let us describe Masha's tree. It has a root at vertex 1. The second line contains n - 1 integers: p2, p3, ..., pn, where pi is the parent of vertex i, the first vertex on a path from vertex i to the root of the tree (1 ≤ pi < i).
The following m lines contain three integers ui, vi, and ci: pairs of vertices to be connected by the additional edges that Masha can add to the tree, and the beauty of the edge (1 ≤ ui, vi ≤ n; ui ≠ vi; 1 ≤ ci ≤ 10^4).
It is guaranteed that no additional edge coincides with an edge of the tree.
Output
Output one integer: the maximum beauty of a cactus Masha can achieve.