Salty Fish
Time limit3sMemory limit512 MB
Pick which cameras to lock so that the apples on nodes seen only by locked cameras, minus the locking costs, is maximized.
- Level
Hard10 of 10
- Topics
- Tree, Dynamic programming
- Solved
- No attempts yet
Statement
Little Q has an apple tree with nodes, labeled . The root is node 1, and each edge has length one. Node has apples. Each apple sells for one dollar, so selling apples earns dollars.
Skywalkert, a close friend of Little Q, lost most of his money betting on programming contests. He wants to steal some apples from this tree and sell them to make money.
The security system takes pictures of the nodes once per hour using cameras. Let be the number of edges on the shortest path from node to node , and let . Note that . The image from the -th camera shows all nodes in . If the security system detects a change in any of these images, it sounds an alarm, and Little Q catches the thief.
Skywalkert is also a gifted hacker. He can lock some cameras so that their images never change. To lock the -th camera, he pays dollars. Skywalkert pays for all hacks after he steals the apples and sells them.
Write a program that helps Skywalkert earn the most money possible without being caught.
Input
The first line contains (), the number of test cases.
Each test case starts with a line containing and ().
The next line contains integers (), the parents of nodes .
The next line contains integers (), the number of apples on nodes .
Each of the next lines contains three integers , , and (, , ), the parameters of camera .
The sum of over all test cases is at most , and the sum of over all test cases is at most .
Output
For each test case, print one line containing an integer: the maximum amount of dollars Skywalkert can earn.