Unstable Substances
InterviewTime limit1.2sMemory limit256 MB
Each substance conflicts with exactly one other; choose a subset with no conflicting pair to maximize total weight.
- Level
Medium5 of 10
- Topics
- Graph, Dynamic programming, Tree, DFS
- Solved
- No attempts yet
Problem
Scientist X has recently succeeded in synthesizing several kinds of ultra-nanoscale substances. There are substances in total, numbered 1 through . Substance has weight , and exactly one of each substance exists.
Scientist X wants to take some of these substances to the upcoming international conference "Unstable Substances Expo" in a special container, but there is one constraint because the substances are unstable. When substance is placed in the special container together with a particular other substance, it explodes due to its unstable nature. After many experiments, Scientist X found that each substance reacts this way with only one other substance, .
Given this information, Scientist X wants to choose a set of substances that does not cause an explosion and take them in the special container.
For example, suppose three substances were synthesized with weights , , . Let the numbers of the substances they react with be , , .
That is, substance 1 reacts and explodes when it is together with substance 2, substance 2 becomes unstable and explodes when it is together with substance 1, and substance 3 explodes when it is together with substance 2.
In this case substances 1 and 3 are safe together and their total weight is 4. However, taking substance 2 alone gives a total weight of 5, so taking only substance 2 is optimal.
Scientist X wants to find the maximum total weight among sets of substances that do not cause an explosion. Find this value.
Input
The first line gives the number of test cases .
The first line of each test case gives the number of substances . The following lines give and , one per line, in order starting from substance 1.
Output
For each test case, print the maximum total weight among the sets of unstable substances Scientist X can take, one per line.
Constraints
Hint
The sum of weights can exceed .