Domain: Algorithms & Data Structures

## Problem: Maximum Possible Score of One Player Under Greedy Picks

You are given `n` distinct items labeled `1..n`, with exactly one copy of each item. Each item `i` has an integer score `v[i]` (scores may be negative).

Two players, **A** and **B**, each have a complete ranking (a permutation) of the items:

- `A[1..n]`: player A’s preference list from most preferred to least preferred  
- `B[1..n]`: player B’s preference list from most preferred to least preferred

The shop starts with all items available. Over exactly `n` turns, the following happens:

- On each turn, **either** A **or** B visits the shop (the order of visitors is not fixed).
- The visiting player takes the **highest-ranked item in their own list that is still available**.

After `n` turns, all items are taken and each player ends up with a set of items.

Your task: among all possible valid visit orders (i.e., all ways to choose who moves on each turn), compute the **maximum possible total score** of the items obtained by player **A**, where total score is the sum of `v[i]` over items A receives.

It can be proven that different visit orders can lead to different sets for A.

---

### Input

The first line contains an integer `t` — the number of test cases.  
`1 ≤ t ≤ 10^4`

For each test case:

- An integer `n` (`1 ≤ n ≤ 2·10^5`)
- A line with `n` integers `v[1], v[2], ..., v[n]` (`-10^9 ≤ v[i] ≤ 10^9`)
- A line with permutation `A[1..n]` of `1..n`
- A line with permutation `B[1..n]` of `1..n`

Constraint: the sum of `n` over all test cases is at most `2·10^5`.

---

### Output

For each test case, output a single integer: the maximum possible sum of scores of items that player A can end up with.


Grading rubric:
criterion: Does the response define p[i] as Bob’s position of item a[i] in Bob’s permutation?
weight: 10
criterion: Does the response state the DP initialization dp[0] = 0?
weight: 10
criterion: Does the response state that the final answer equals max(dp[j]) over j from 0 to n?
weight: 10
criterion: Does the response specify a segment-tree range-maximum query over the index interval j in [0, p[i]−1] to compute bestPrefix for item i?
weight: 10
criterion: Does the response define a relabeling where item i corresponds to the original item a[i]?
weight: 10
criterion: Does the response define a DP state dp[j] as the maximum total value Alice can obtain with current maximum Bob-rank equal to j?
weight: 10
criterion: Does the response state that assigning item i to Alice is allowed only for DP states with j < p[i]?
weight: 10
criterion: Does the response state that assigning item i to Bob updates the maximum Bob-rank to max(j, p[i])?
weight: 10
criterion: Does the response specify a segment-tree range-add update of +val[i] applied to dp[j] over the index interval j in [0, p[i]−1]?
weight: 10
criterion: Does the response specify the point update dp[p[i]] := max(dp[p[i]], bestPrefix) after processing item i?
weight: 10

Answer:
### 1) Renaming so that Alice’s list becomes `1,2,...,n`

Let the original item IDs be `1..n`. Define:

- `a[1..n]`: Alice’s permutation (most preferred first)
- `b[1..n]`: Bob’s permutation
- `v[id]`: value of item `id`

Relabel items by **Alice-rank**:

- The item with Alice-rank `i` is `id = a[i]`.
- Define `val[i] = v[a[i]]`.
- Let `pos[id]` be Bob’s rank of item `id` in `b` (i.e., `pos[b[j]] = j`).
- Define `p[i] = pos[a[i]]`.

After this transformation, we can think of items as `1..n` in Alice’s priority order, with:
- value `val[i]`
- Bob-rank `p[i]`

This does not change which outcomes are possible; it only renames items.

---

### 2) Which subsets can Alice end up with?

Suppose Alice finally gets a set `S` of Alice-ranks. Consider any pair:
- `x ∉ S` (Bob gets `x`)
- `y ∈ S` (Alice gets `y`)
with `x < y` (Alice likes `x` more than `y`).

A necessary condition is:

> `p[x] < p[y]`.

Reason:  
If `p[x] > p[y]`, then Bob prefers `y` earlier than `x`, but Alice prefers `x` earlier than `y`. Under greedy picking, neither `x` nor `y` can be taken first without blocking the other, so such a final split is impossible.

It turns out this condition is also sufficient: if it holds for all such pairs, a valid visit order exists that realizes exactly `S` (you can schedule Bob to “clear” items until Alice’s next desired item becomes her current greedy choice).

So the problem becomes:

> Choose a subset `S` maximizing `sum(val[i] for i in S)` such that  
> for every `x ∉ S`, `y ∈ S`, `x < y` implies `p[x] < p[y]`.

---

### 3) DP formulation using the maximum Bob-rank seen so far

Process items in increasing Alice-rank `i = 1..n`.

Let `dp[j]` mean:

- after deciding ownership of the first `i` items,
- the maximum Bob-rank among items assigned to Bob equals `j`,
- `dp[j]` is the maximum achievable sum of values assigned to Alice.

Here `j` ranges from `0..n`, where `j = 0` means Bob has taken nothing yet.

Initialization:
- `dp[0] = 0`
- `dp[j] = -∞` for `j > 0`

Now process item `i` with Bob-rank `p = p[i]` and value `val = val[i]`.

**Case A: Alice takes item `i`**  
This is allowed exactly when `p > j` (all earlier Bob-taken items have smaller Bob-rank).  
State `j` stays the same, value increases:

- for all `j < p`: `dp_next[j] = dp[j] + val`

**Case B: Bob takes item `i`**  
Value does not change, new max Bob-rank becomes `max(j, p)`:

- if `j ≥ p`: it remains in state `j`
- if `j < p`: it moves to state `p`

---

### 4) Segment tree optimization (O(n log n))

The transition above can be implemented in-place on a segment tree over indices `j = 0..n` storing current `dp[j]`.

For item `(p, val)`:

1. Compute:
   - `bestPrefix = max(dp[j])` over `j in [0, p-1]`

2. Apply Alice-taking updates:
   - For all `j in [0, p-1]`, do `dp[j] += val`
   - This is a **range add**.

3. Apply Bob-taking update into state `p`:
   - `dp[p] = max(dp[p], bestPrefix)`
   - This is a **point chmax** after a range max query.

Note:
- States `j > p` are unchanged in this step.
- State `p` already contains the `j = p` “Bob keeps max = p” option, and the `bestPrefix` handles all `j < p` moving into `p`.

After processing all `n` items, the answer is:
- `max(dp[j])` over `j = 0..n`

Data structure requirements:
- range add
- range maximum query
- point update to set `dp[p] := max(dp[p], x)`

A lazy segment tree supports these in `O(log n)` each, giving total complexity `O(n log n)` per test file (with `sum n ≤ 2·10^5`).

---

### 5) Summary of implementation steps

For each test case:
1. Read `v`, `a`, `b`.
2. Build `pos[id]` from `b`.
3. Build arrays for `i = 1..n`:
   - `val[i] = v[a[i]]`
   - `p[i] = pos[a[i]]`
4. Initialize segment tree with `dp[0]=0`, others `-∞`.
5. For `i=1..n`, perform the three operations described above.
6. Output the maximum stored `dp[j]`.