Codeforces Round 1091 (Div. 2) and CodeCraft 26
H
Closer
Codeforces
2800
原题
← G→
翻译中…

At your networking event, there are $n$ deals waiting to happen.

翻译中…

Each deal needs exactly two people, and every person is waiting for exactly one deal. So there are $2n$ people in total, and each deal ID $1 \ldots n$ appears on exactly two people's badges.

翻译中…

For corporate reasons, the organisers place each person on a unique vertex in a tree with $2n$ vertices. Vertex $v$ hosts a person with badge $a_v$.

翻译中…

Deal $i$ is sealed if, when the event begins, the two people with badge $i$ are on adjacent vertices. Each sealed deal contributes $w_i$ to your earnings.

翻译中…

Before the event starts, you are allowed one reshuffle:

翻译中…
  1. Choose any (potentially empty) set of edges such that no two chosen edges share a vertex (i.e., the edges form a matching).
  2. For every chosen edge $(u, v)$, swap the people at vertices $u$ and $v$.
翻译中…

After reshuffling, what is the maximum you can earn from this event?

翻译中…

Input

翻译中…

Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 10^4$). The description of the test cases follows.

翻译中…

The first line of each test case contains a single integer $n$ ($1 \leq n \leq 10^5$).

翻译中…

The next line contains $n$ integers $w_1, w_2, \ldots, w_n$ ($0 \leq w_i \leq 10^5$), where $w_i$ denotes the profit from deal $i$.

翻译中…

The next line contains $2n$ integers $a_1, a_2, \ldots, a_{2n}$. It is guaranteed that each value $1, 2, \ldots, n$ appears exactly twice in $a$.

翻译中…

The next $2n-1$ lines each contain two integers $u$ and $v$ ($1 \leq u, v, \leq 2n, u \neq v$) — denoting that an edge connects nodes $u$ and $v$.

翻译中…

It is guaranteed that the sum of $n$ over all test cases does not exceed $10^5$.

翻译中…

Output

翻译中…

For each test case, output a single integer — the maximum total earning after a reshuffle.

翻译中…

Note

翻译中…

Test 1. Swap edges $(1,2)$ and $(3,4)$ (they don't share vertices). Then the two 1s become adjacent on edge $(2,3)$, earning $w_1=10$, which beats keeping the existing 2—2 adjacency worth 3.

翻译中…

Test 2. The tree is a star. Swapping $(1,2)$ moves badge 1 to the center, making it adjacent to the other 1, earning $w_1=8$.

翻译中…

Test 3. Swap $(1,2), (3,4), (5,6)$ to seal two deals at once: edge $(2,3)$ becomes 1—1 (gain 4) and edge $(4,5)$ becomes 3—3 (gain 7), total 11.

翻译中…

样例

Input #1
3
2
10 3
1 2 2 1
1 2
2 3
3 4
3
8 7 1
3 1 2 3 1 2
1 2
1 3
1 4
1 5
1 6
3
4 9 7
1 2 3 1 2 3
1 2
2 3
3 4
4 5
5 6
Output #1
10
8
11
InputCopy OutputCopy
题目信息
题号
2217H
时间限制
3 s
内存限制
512 MB
标签
DFS 及类似
动态规划
树

题面与样例版权归 Codeforces 及出题人所有;中文翻译由 AI 生成(CI 管线),如有出入请以原文为准。