Under construction

Still being built. Things may change

Unstable Substances

Interview

Time limit1.2sMemory limit256 MB

Summary
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 nn substances in total, numbered 1 through nn. Substance ii has weight wiw_i, 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 ii 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 ii reacts this way with only one other substance, QiQ_i.

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 w1=3w_1 = 3, w2=5w_2 = 5, w3=1w_3 = 1. Let the numbers of the substances they react with be Q1=2Q_1 = 2, Q2=1Q_2 = 1, Q3=2Q_3 = 2.

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 TT.

The first line of each test case gives the number of substances nn. The following nn lines give wiw_i and QiQ_i, 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

  • 1≤T≤101 \le T \le 10
  • 2≤n≤100,0002 \le n \le 100{,}000
  • 1≤wi≤1,000,0001 \le w_i \le 1{,}000{,}000
  • 1≤Qi≤n1 \le Q_i \le n
  • Qi≠iQ_i \ne i

Hint

The sum of weights can exceed 231−12^{31}-1.

Examples1

  1. Example 1

    Input
    4
    3
    3 2
    5 1
    1 2
    3
    3 2
    2 3
    2 1
    4
    1 3
    2 3
    3 4
    4 2
    4
    2 2
    3 1
    4 4
    3 3
    
    Expected output
    5
    3
    5
    7