#P7443. 「EZEC-7」加边
「EZEC-7」加边
Background
How do you do brute force? Brute force is, add edges! Add edges! Add edges! Then query with DSU!
Alice does not like DSU (Disjoint Set Union), but she likes adding edges.
Problem Description
Given a tree with nodes, the nodes are numbered starting from . Node is the root. Each edge is directed from the parent to the child. Each node has a weight . Alice and Bob are playing a game: they place a token on the root node. Alice and Bob take turns moving the token along directed edges. Whoever cannot move loses.
It is known whether Alice moves first or second. Before the game starts, Alice may add one directed edge (), and then they play the game on the resulting graph. She wants to have a winning strategy. She may also choose not to add an edge. If the winner cannot be determined, it does not count as a win.
Given positive integers , the cost for Alice to add an edge is . The cost of choosing not to add an edge is .
Alice wants to minimize her cost. If no matter how she adds an edge she cannot meet the requirement, output .
Alice will make queries. You need to output the answer for each query.
Input Format
This problem has multiple test cases.
The first line contains a positive integer , the number of queries.
For each query, the first line contains four positive integers , where is the number of nodes in the tree, and indicates the move order: means Alice moves first, and means Alice moves second.
The next line contains positive integers. The -th number is the parent index of node .
The next line contains positive integers. The -th number is the value of .
Output Format
For each query, output one integer per line, the minimum cost for Alice. If no matter how she adds an edge she cannot meet the requirement, output .
4
3 1 2 7
1 1
4 3 2
3 1 2 7
1 2
4 3 2
3 0 2 7
1 2
4 3 2
9 1 523 182
1 1 2 2 2 3 3 1
3 23 18 293 162 483 574 384 109
-1
0
22
86491
Hint
[Sample Explanation]
In the -st query, Alice moves second. No matter how she adds an edge, she cannot have a winning strategy, so output .
In the -nd query, Alice moves second. She already has a winning strategy without adding an edge, so the cost is .
In the -rd query, Alice moves first. She can only add an edge to guarantee a win. The cost is .
In the -th query, Alice moves second. She can add an edge to guarantee a win. The cost is . She has other ways to guarantee a win, but is the minimum cost.
[Constraints]
This problem uses bundled testdata.
- Subtask 1 (10 points): , .
- Subtask 2 (15 points): .
- Subtask 3 (15 points): .
- Subtask 4 (10 points): .
- Subtask 5 (10 points): .
- Subtask 6 (20 points): .
- Subtask 7 (20 points): no special restrictions.
For of the data, , , , , , .
[Hint]
Please use a fast input method.
Translated by ChatGPT 5