Under construction

Still being built. Things may change

Square Graph

Time limit5sMemory limit256 MB

Summary
Given a sequence and a weight for each half-length k, find the minimum spanning forest weight of the graph built from squares whose two halves match.
Level

Hard8 of 10

Topics
String matching, Union-find, Greedy, Sorting
Solved
No attempts yet

Problem

Prof. Elephant has a sequence a_1,a_2,…,a_na\_1, a\_2, \ldots, a\_n. He used the sequence to generate an undirected graph GG with nn vertices labeled 1,2,…,n1, 2, \ldots, n.

For each even-length contiguous subsequence a_l,a_l+1,…,a_l+2k−1a\_l, a\_{l + 1}, \ldots, a\_{l + 2 k - 1}, check whether a_l+i−1=a_l+k+i−1a\_{l + i - 1} = a\_{l + k + i - 1} holds for every i=1,2,…,ki = 1, 2, \ldots, k. If it does, Prof. Elephant adds kk edges to GG. The ii-th edge connects vertices (l+i−1)(l + i - 1) and (l+k+i−1)(l + k + i - 1), and its weight is w_kw\_k.

Prof. Elephant wants to know the total weight of the minimum spanning forest of GG.

Input

There are multiple test cases. The first line contains an integer TT, the number of test cases. Each test case is given as follows.

The first line contains an integer nn (2≤n≤3×1052 \leq n \leq 3 \times 10^5).

The second line contains nn integers a_1,a_2,…,a_na\_1, a\_2, \ldots, a\_n (1≤a_i≤n1 \leq a\_i \leq n).

The third line contains ⌊n2⌋\lfloor\frac{n}{2}\rfloor integers w_1,w_2,…,w_⌊n2⌋w\_1, w\_2, \ldots, w\_{\lfloor\frac{n}{2}\rfloor} (1≤w_i≤1091 \leq w\_i \leq 10^9).

The sum of nn over all test cases does not exceed 3×1053 \times 10^5.

Output

For each test case, output one integer: the total weight of the minimum spanning forest of GG.

Examples1

  1. Example 1

    Input
    1
    8
    2 2 5 6 2 5 6 2
    5 1 4 4
    
    Expected output
    21