ZOJ Problem Set - 3910
There's a fruit market in Byteland. The salesmen there only sell apples.
There are n salesmen in the fruit market and the i-th salesman will sell at most wi apples. Every salesman has an immediate manager pi except one salesman who is the boss of the market. A salesman A is said to be the superior of another salesman B if at least one of the followings is true:
The market will not have a managerial cycle. That is, there will not exist a salesman who is the superior of his/her own immediate manager.
We will call salesman x a subordinate of another salesman y, if either y is an immediate manager of x, or the immediate manager of x is a subordinate to salesman y. In particular, subordinates of the boss are all other salesmen of the market. Let the degree of the boss be 0. Then if the degree of i-th salesman is k, the immediate subordinates of i-th salesman will have degree k + 1.
Today, m buyers come to market for apples. The i-th buyer will buy at most ci apples only from the xi-th salesman and his subordinates whose degree is no larger than xi-th salesman's degree plus di.
The boss wants to know how many apples can be sold in salesmen's best effort (i.e. the maximum number).
There are multiple test cases. The first line of input contains an integer T indicating the number of test cases. For each test case:
The first line contains two integers n and m (1 ≤ n, m ≤ 10000) — the number of salesmen and the number of buyers.
The second line contains n integers w1, w2, ..., wn (1 ≤ wi ≤ 105). Every wi denotes the number of apples that i-th salesman can sell.
The next line contains n integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th salesman. If pi is -1, that means that the i-th salesman does not have an immediate manager.
Each of the next m lines contains three integers ci, xi and di (1 ≤ ci ≤ 105, 1 ≤ xi ≤ n, 0 ≤ di ≤ n) — the information of i-th buyer.
It is guaranteed that the total number of salesmen in the input doesn't exceed 105, and the total number of buyers also doesn't exceed 105. The number of test cases in the input doesn't exceed 500.
For each test case, output a single integer denoting the maximum number of apples can be sold.
1 4 2 1 2 3 4 -1 1 2 3 3 2 1 5 1 1
Author: LIN, Xi
Source: ZOJ Monthly, October 2015