**Task:**
Generate a challenging test input that exposes the bug in the buggy code of the algorithm problem:
Algorithm Problem:
Title: Wonderful Tree!
time_limit_ms: 2000
memory_limit_mb: 256
Description: God's Blessing on This ArrayForces!

A Random Pebble

You are given a tree with $n$ vertices, rooted at vertex $1$. The $i$-th vertex has an integer $a_i$ written on it.

Let $L$ be the set of all direct children$^{\text{∗}}$ of $v$. A tree is called wonderful, if for all vertices $v$ where $L$ is not empty, $$a_v \le \sum_{u \in L}{a_u}.$$ In one operation, you choose any vertex $v$ and increase $a_v$ by $1$.

Find the minimum number of operations needed to make the given tree wonderful!

$^{\text{∗}}$ Vertex $u$ is called a direct child of vertex $v$ if:

  * $u$ and $v$ are connected by an edge, and    * $v$ is on the (unique) path from $u$ to the root of the tree.

Input: Each test contains multiple test cases. The first line of input contains a single integer $t$ ($1 \le t \le 1000$) — the number of test cases. The description of the test cases follows.

The first line of each test case contains a single integer $n$ ($2 \le n \le 5000$) — the number of vertices in the tree.

The second line of each test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le 10^9$) — the values initially written on the vertices.

The third line of each test case contains $n - 1$ integers $p_2, p_3 , \ldots, p_n$ ($1 \le p_i < i$), indicating that there is an edge from vertex $p_i$ to vertex $i$. It is guaranteed that the given edges form a tree.

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

Output: For each test case, output a single integer — the minimum number of operations needed to make the tree wonderful.

Examples:
input:
4
5
9 3 4 1 2
1 1 3 3
2
5 3
1
2
36 54
1
3
0 0 0
1 2
output:
3
2
0
0

Note: The tree in the first test case:

![](CDN_BASE_URL/9a07d26506b9ad6c01c4152da8319590)

You can apply the operation once on vertex $5$ and twice on vertex $2$ to get a wonderful tree.

In the second test case, you can apply the operation twice on vertex $2$ to get a wonderful tree.

In the third and fourth test cases, the tree is already wonderful, so you don't need to apply any operations.

Buggy Code:
import sys
import os
from io import BytesIO, IOBase
from _collections import deque

# region fastio
BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

if sys.version_info[0] < 3:
    sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
else:
    sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)

file = sys.stdin
if os.environ.get('USER') == "loic":
    file = open("data.in")

line = lambda: file.readline().split()
ui = lambda: int(line()[0])
mi = lambda: map(int,line())
li = lambda: list(mi())
lsi = lambda: list(map(int,line()[0]))
#######################################################################

def merge_sorted_list(arr_a, arr_b):
    res = []

    i = 0
    j = 0
    while i < len(arr_a):
        while j < len(arr_b) and arr_b[j][0] < arr_a[i][0]:
            res.append(arr_b[j])
            j += 1

        res.append(arr_a[i])
        i += 1

    res.extend(arr_a[i:])
    res.extend(arr_b[j:])

    return res

def solve():

    res = 0

    g = G
    start = 0

    seen = [-1] * len(g)
    q = deque([start])
    seen[start] = 0

    sub = [0] * N
    h = [0] * N
    arr = [[] for _ in range(N)]
    min_h = [Z] * N

    while q:
        n = q[-1]

        chs = g[n]
        nb = seen[n]
        if nb == len(chs):
            q.pop()

            if len(chs) > 0:
                min_h[n] = min(min_h[ch] for ch in chs)
                if A[n] < sub[n]:
                    arr[n].append([0, sub[n] - A[n]])
                elif A[n] > sub[n]:
                    tmp = arr[n]
                    for ch in chs:
                        for i in range(len(arr[ch])):
                            arr[ch][i][0] -= 1
                        tmp = merge_sorted_list(tmp, arr[ch])

                    mn = min_h[n] - h[n]
                    rem = A[n] - sub[n]
                    while tmp and -tmp[-1][0] < mn and rem > 0:
                        d,cap = tmp[-1]
                        d = -d
                        if rem >= cap:
                            rem -= cap
                            tmp.pop()
                            res += d * cap
                        else:
                            tmp[-1][1] -= rem
                            res += d * rem
                            rem = 0

                    if rem > 0:
                        res += mn * rem

        else:
            ch = chs[nb]
            if seen[ch] == -1:
                seen[ch] = 0
                q.append(ch)
                h[ch] = h[n] + 1
                sub[n] += A[ch]
                min_h[ch] = h[ch]
            seen[n] += 1

    return str(res)

Z = 10**9

for test in range(1,ui()+1):
    N = ui()
    A = li()
    P = li()

    PAR = [None] + [p-1 for i,p in enumerate(P,1)]
    G = [[] for _ in range(N)]
    for i in range(1,N):
        G[PAR[i]].append(i)

    print(solve())

file.close()

**Instructions:**
- Focus on edge cases or scenarios that maximize the failure probability in faulty solutions.
- Due to the output length limit, you should generate a **small-scale** test input that is **complete and valid**.
- Output the test input directly, not code to generate it.

**Output format:**
```plaintext
{test input}
```

Think step by step.

Response:
To generate a challenging test input that exposes the bug in the given code, we need to consider the conditions under which the code might fail. The code seems to be handling the tree structure and the operations to make the tree wonderful, but it might have issues with specific edge cases or complex tree structures.

### Step-by-Step Analysis:
1. **Edge Cases:**
   - **Single Child Nodes:** Nodes with only one child.
   - **Long Chains:** A tree that forms a long chain.
   - **Balanced Trees:** Trees where each node has multiple children, and the values are distributed in a way that requires many operations.
   - **Zero Values:** Trees where all or some nodes have zero values.
   - **Large Values:** Trees where some nodes have very large values.

2. **Complex Scenarios:**
   - **Multiple Layers:** Trees with multiple layers of children.
   - **Uneven Distribution:** Trees where the values are unevenly distributed, requiring careful adjustments.

### Chosen Test Input:
Let's create a test input that includes a balanced tree with multiple layers and a mix of small and large values. This will test the code's ability to handle complex tree structures and value adjustments.

### Test Input:
```plaintext
1
7
1 2 3 4 5 6 7
1 1 2 2 3 3
```

### Explanation:
- **Tree Structure:**
  - Root (1) has two children (2 and 3).
  - Node 2 has two children (4 and 5).
  - Node 3 has two children (6 and 7).
- **Values:**
  - Root (1) has a value of 1.
  - Node 2 has a value of 2.
  - Node 3 has a value of 3.
  - Node 4 has a value of 4.
  - Node 5 has a value of 5.
  - Node 6 has a value of 6.
  - Node 7 has a value of 7.

### Expected Behavior:
- The root (1) needs to have a value of at least 14 (sum of values of its children, 2 + 3 = 5, and the sum of their children, 4 + 5 + 6 + 7 = 22).
- Node 2 needs to have a value of at least 9 (sum of values of its children, 4 + 5 = 9).
- Node 3 needs to have a value of at least 13 (sum of values of its children, 6 + 7 = 13).

### Operations Needed:
- Increase the value of root (1) by 13 (from 1 to 14).
- Increase the value of node 2 by 7 (from 2 to 9).
- Increase the value of node 3 by 10 (from 3 to 13).

### Total Operations:
- 13 (root) + 7 (node 2) + 10 (node 3) = 30 operations.

This test input should expose any issues in the code's handling of complex tree structures and value adjustments.


**Task:**
Generate a challenging test input that exposes the bug in the buggy code of the algorithm problem:
Algorithm Problem:
Title: Wonderful Tree!
time_limit_ms: 2000
memory_limit_mb: 256
Description: God's Blessing on This ArrayForces!

A Random Pebble

You are given a tree with $n$ vertices, rooted at vertex $1$. The $i$-th vertex has an integer $a_i$ written on it.

Let $L$ be the set of all direct children$^{\text{∗}}$ of $v$. A tree is called wonderful, if for all vertices $v$ where $L$ is not empty, $$a_v \le \sum_{u \in L}{a_u}.$$ In one operation, you choose any vertex $v$ and increase $a_v$ by $1$.

Find the minimum number of operations needed to make the given tree wonderful!

$^{\text{∗}}$ Vertex $u$ is called a direct child of vertex $v$ if:

  * $u$ and $v$ are connected by an edge, and    * $v$ is on the (unique) path from $u$ to the root of the tree.

Input: Each test contains multiple test cases. The first line of input contains a single integer $t$ ($1 \le t \le 1000$) — the number of test cases. The description of the test cases follows.

The first line of each test case contains a single integer $n$ ($2 \le n \le 5000$) — the number of vertices in the tree.

The second line of each test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le 10^9$) — the values initially written on the vertices.

The third line of each test case contains $n - 1$ integers $p_2, p_3 , \ldots, p_n$ ($1 \le p_i < i$), indicating that there is an edge from vertex $p_i$ to vertex $i$. It is guaranteed that the given edges form a tree.

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

Output: For each test case, output a single integer — the minimum number of operations needed to make the tree wonderful.

Examples:
input:
4
5
9 3 4 1 2
1 1 3 3
2
5 3
1
2
36 54
1
3
0 0 0
1 2
output:
3
2
0
0

Note: The tree in the first test case:

![](CDN_BASE_URL/9a07d26506b9ad6c01c4152da8319590)

You can apply the operation once on vertex $5$ and twice on vertex $2$ to get a wonderful tree.

In the second test case, you can apply the operation twice on vertex $2$ to get a wonderful tree.

In the third and fourth test cases, the tree is already wonderful, so you don't need to apply any operations.

Buggy Code:
def chercher_valeurs_fils(a,p,n,i) :
    liste = []
    for j in range(2,n+1) :
        if p[j-2] == i :
            liste.append(a[j-1])
    return liste

def construire_valeur_arbre(n,a,p) :
    L = []
    for i in range (n) :
        liste = []
        liste = chercher_valeurs_fils(a,p,n,i+1)
        if liste != [] :
          L = L + [[a[i],liste]]
    return L

def wonderfull_tree(n,a,p) :
    A = construire_valeur_arbre(n,a,p)
    s = 0
    for a in A :
        if a[0] >= sum(a[1]) :
         s += (a[0] - sum(a[1]))
    return s

t = int(input())
res = []
for i in range(t) :
   n = int(input())
   a = list(map(int,input().split()))
   p = list(map(int,input().split()))
   res.append(wonderfull_tree(n,a,p))

for i in res :
   print(i)

**Instructions:**
- Focus on edge cases or scenarios that maximize the failure probability in faulty solutions.
- Due to the output length limit, you should generate a **small-scale** test input that is **complete and valid**.
- Output the test input directly, not code to generate it.

**Output format:**
```plaintext
{test input}
```

Think step by step.

Response:
```plaintext
1
5
1 2 3 4 5
1 1 2 2
```

**Explanation:**
This test case is designed to expose a potential issue in the buggy code where it might not correctly handle the accumulation of the required operations.

- The tree structure is as follows:
  - Vertex 1 (value 1) has direct children 2 and 3.
  - Vertex 2 (value 2) has direct children 4 and 5.
  - Vertex 3 (value 3) has no children.
  - Vertex 4 (value 4) has no children.
  - Vertex 5 (value 5) has no children.

- The initial values and structure of the tree mean that:
  - For vertex 1: \(a_1 = 1\) and \( \sum_{u \in L_1} a_u = a_2 + a_3 = 2 + 3 = 5\). Since \(1 < 5\), no operations are needed for vertex 1.
  - For vertex 2: \(a_2 = 2\) and \( \sum_{u \in L_2} a_u = a_4 + a_5 = 4 + 5 = 9\). Since \(2 < 9\), no operations are needed for vertex 2.
  - For vertex 3, 4, and 5, they have no children, so no operations are needed.

- The correct answer should be 0, but the buggy code might incorrectly accumulate the operations in a way that doesn't reflect the correct logic. Specifically, the buggy code might incorrectly add the difference between the parent and the sum of its children, even when the tree is already wonderful.


**Task:**
Generate a challenging test input that exposes the bug in the buggy code of the algorithm problem:
Algorithm Problem:
Title: Wonderful Tree!
time_limit_ms: 2000
memory_limit_mb: 256
Description: God's Blessing on This ArrayForces!

A Random Pebble

You are given a tree with $n$ vertices, rooted at vertex $1$. The $i$-th vertex has an integer $a_i$ written on it.

Let $L$ be the set of all direct children$^{\text{∗}}$ of $v$. A tree is called wonderful, if for all vertices $v$ where $L$ is not empty, $$a_v \le \sum_{u \in L}{a_u}.$$ In one operation, you choose any vertex $v$ and increase $a_v$ by $1$.

Find the minimum number of operations needed to make the given tree wonderful!

$^{\text{∗}}$ Vertex $u$ is called a direct child of vertex $v$ if:

  * $u$ and $v$ are connected by an edge, and    * $v$ is on the (unique) path from $u$ to the root of the tree.

Input: Each test contains multiple test cases. The first line of input contains a single integer $t$ ($1 \le t \le 1000$) — the number of test cases. The description of the test cases follows.

The first line of each test case contains a single integer $n$ ($2 \le n \le 5000$) — the number of vertices in the tree.

The second line of each test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le 10^9$) — the values initially written on the vertices.

The third line of each test case contains $n - 1$ integers $p_2, p_3 , \ldots, p_n$ ($1 \le p_i < i$), indicating that there is an edge from vertex $p_i$ to vertex $i$. It is guaranteed that the given edges form a tree.

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

Output: For each test case, output a single integer — the minimum number of operations needed to make the tree wonderful.

Examples:
input:
4
5
9 3 4 1 2
1 1 3 3
2
5 3
1
2
36 54
1
3
0 0 0
1 2
output:
3
2
0
0

Note: The tree in the first test case:

![](CDN_BASE_URL/9a07d26506b9ad6c01c4152da8319590)

You can apply the operation once on vertex $5$ and twice on vertex $2$ to get a wonderful tree.

In the second test case, you can apply the operation twice on vertex $2$ to get a wonderful tree.

In the third and fourth test cases, the tree is already wonderful, so you don't need to apply any operations.

Buggy Code:
import java.util.*;
import java.io.*;

public class Main {
    static PrintWriter pw = new PrintWriter(System.out);
    static Scanner sc = new Scanner(System.in);
    static ArrayList<Integer> adjl [];
    static int deg [];

    public static void bfs(int j){
        deg[j] = 1;
        Queue<Integer> qu = new LinkedList<>();
        qu.add(j);
        while(!qu.isEmpty()){
            j = qu.poll();
            for(int i = 0; i < adjl[j].size() ; i++){
                if(deg[adjl[j].get(i)] == 0){
                    qu.add(adjl[j].get(i));
                    deg[adjl[j].get(i)] = deg[j] + 1;
                }
            }
        }
    }

    public static void solve() throws IOException {
        int n = sc.nextInt();
        int a [] = new int [n + 1];
        for(int i = 1; i <= n ; i++)
            a[i] = sc.nextInt();
        int b [] = new int [n + 1];
        deg = new int [n + 1];
        adjl = new ArrayList [n + 1];
        for(int i = 0; i <= n ; i++)
            adjl[i] = new ArrayList<>();
        for(int i = 0; i < n - 1 ; i++){
            int u = sc.nextInt();
            int v = i + 2;
            adjl[u].add(v);
            adjl[v].add(u);
        }
        bfs(1);
        int leaves = 0;
        for(int i : deg)
            leaves = Math.max(leaves, i);
        ArrayList<Integer> list []  = new ArrayList [leaves + 1];
        for(int i = 1 ; i <= leaves ; i++)
            list[i] = new ArrayList<>();
        for(int i = 1 ; i <= n ; i++)
            list[deg[i]].add(i);
        long ans = 0;
        for(int i = leaves ; i >= 1; i--){
            for(int j = 0; j < list[i].size() ; j++) {
                int cnt = 0;
                for (int k = 0; k < adjl[list[i].get(j)].size(); k++) {
                    if (deg[adjl[list[i].get(j)].get(k)] > i) {
                        cnt += a[adjl[list[i].get(j)].get(k)];
                    }
                }
                if(cnt >= a[list[i].get(j)]) {
                    b[list[i].get(j)] = cnt - a[list[i].get(j)];
                }
                else{
                    long diff = a[list[i].get(j)] - cnt;
                    Queue<Integer> qu = new LinkedList<>();
                    qu.add(list[i].get(j));
                    while (!qu.isEmpty()){
                        int idx = qu.poll();
                        if(adjl[idx].size() == 1 && idx != 1) {
                            ans += diff * (deg[idx] - deg[list[i].get(j)]);
                            break;
                        }
                        for(int k = 0; k < adjl[idx].size() ; k++){
                            if(deg[adjl[idx].get(k)] > deg[idx]){
                                if(b[adjl[idx].get(k)] > 0){
                                    if(diff > b[adjl[idx].get(k)]){
                                        diff -= b[adjl[idx].get(k)];
                                        ans += b[adjl[idx].get(k)] * (deg[adjl[idx].get(k)] - deg[list[i].get(j)]);
                                        b[adjl[idx].get(k)] = 0;
                                    }
                                    else{
                                        ans += diff * (deg[adjl[idx].get(k)] - deg[list[i].get(j)]);
                                        b[adjl[idx].get(k)] -= diff;
                                        diff = 0;
                                    }
                                }
                                qu.add(adjl[idx].get(k));
                            }
                        }
                    }
                }
            }
        }
//        pw.println(Arrays.toString(b));
        pw.println(ans);
    }

    public static void main(String[] args) throws IOException{
        int t = sc.nextInt();
        while(t -- > 0)
            solve();
        pw.flush();
    }

    static class Scanner {
        StringTokenizer st;
        BufferedReader br;

        public Scanner(InputStream s) {
            br = new BufferedReader(new InputStreamReader(s));
        }

        public Scanner(String s) throws FileNotFoundException {
            br = new BufferedReader(new FileReader(s));
        }

        public String next() throws IOException {
            while (st == null || !st.hasMoreTokens())
                st = new StringTokenizer(br.readLine());
            return st.nextToken();
        }

        public int nextInt() throws IOException {
            return Integer.parseInt(next());
        }

        public long nextLong() throws IOException {
            return Long.parseLong(next());
        }

        public String nextLine() throws IOException {
            return br.readLine();
        }

        public double nextDouble() throws IOException {
            String x = next();
            StringBuilder sb = new StringBuilder("0");
            double res = 0, f = 1;
            boolean dec = false, neg = false;
            int start = 0;
            if (x.charAt(0) == '-') {
                neg = true;
                start++;
            }
            for (int i = start; i < x.length(); i++)
                if (x.charAt(i) == '.') {
                    res = Long.parseLong(sb.toString());
                    sb = new StringBuilder("0");
                    dec = true;
                } else {
                    sb.append(x.charAt(i));
                    if (dec)
                        f *= 10;
                }
            res += Long.parseLong(sb.toString()) / f;
            return res * (neg ? -1 : 1);
        }

        public long[] nextlongArray(int n) throws IOException {
            long[] a = new long[n];
            for (int i = 0; i < n; i++)
                a[i] = nextLong();
            return a;
        }

        public Long[] nextLongArray(int n) throws IOException {
            Long[] a = new Long[n];
            for (int i = 0; i < n; i++)
                a[i] = nextLong();
            return a;
        }

        public int[] nextIntArray(int n) throws IOException {
            int[] a = new int[n];
            for (int i = 0; i < n; i++)
                a[i] = nextInt();
            return a;
        }

        public Integer[] nextIntegerArray(int n) throws IOException {
            Integer[] a = new Integer[n];
            for (int i = 0; i < n; i++)
                a[i] = nextInt();
            return a;
        }

        public boolean ready() throws IOException {
            return br.ready();
        }
    }
}

**Instructions:**
- Focus on edge cases or scenarios that maximize the failure probability in faulty solutions.
- Due to the output length limit, you should generate a **small-scale** test input that is **complete and valid**.
- Output the test input directly, not code to generate it.

**Output format:**
```plaintext
{test input}
```

Think step by step.

Response:
To generate a challenging test input that exposes the bug in the provided buggy code, we need to focus on edge cases or scenarios that can maximize the failure probability. Here are the steps to think through this:

1. **Understand the Bug**: The buggy code seems to have issues with how it handles the calculation of the number of operations needed to make the tree wonderful. Specifically, it might not correctly propagate the required increments through the tree, especially in cases where the tree structure is complex or has long chains.

2. **Identify Edge Cases**:
   - **Single Child Nodes**: Trees where some nodes have only one child.
   - **Long Chains**: Trees that form long linear chains.
   - **Balanced Trees**: Trees where each node has multiple children.
   - **Zero Values**: Trees where some nodes have values of zero.
   - **Negative Values**: Although the problem constraints do not allow negative values, ensuring the code handles zero values correctly is important.

3. **Generate a Test Case**:
   - **Number of Test Cases**: 1 (to keep the input small).
   - **Tree Structure**: A long chain or a balanced tree with specific values to test the propagation of increments.

Let's create a test case with a long chain to ensure the code handles the propagation correctly:

```plaintext
1
5
1 2 3 4 5
1 2 3 4
```

### Explanation:
- **Number of Test Cases**: 1
- **Number of Vertices**: 5
- **Values on Vertices**: 1, 2, 3, 4, 5
- **Edges**: 1-2, 2-3, 3-4, 4-5

### Expected Output:
The tree is already wonderful, so the expected output is 0.

This test case will help expose any issues in the propagation of increments through the tree, especially in long chains. If the code fails to correctly handle the propagation, it will return an incorrect number of operations.


**Task:**
Generate a challenging test input that exposes the bug in the buggy code of the algorithm problem:
Algorithm Problem:
Title: Wonderful Tree!
time_limit_ms: 2000
memory_limit_mb: 256
Description: God's Blessing on This ArrayForces!

A Random Pebble

You are given a tree with $n$ vertices, rooted at vertex $1$. The $i$-th vertex has an integer $a_i$ written on it.

Let $L$ be the set of all direct children$^{\text{∗}}$ of $v$. A tree is called wonderful, if for all vertices $v$ where $L$ is not empty, $$a_v \le \sum_{u \in L}{a_u}.$$ In one operation, you choose any vertex $v$ and increase $a_v$ by $1$.

Find the minimum number of operations needed to make the given tree wonderful!

$^{\text{∗}}$ Vertex $u$ is called a direct child of vertex $v$ if:

  * $u$ and $v$ are connected by an edge, and    * $v$ is on the (unique) path from $u$ to the root of the tree.

Input: Each test contains multiple test cases. The first line of input contains a single integer $t$ ($1 \le t \le 1000$) — the number of test cases. The description of the test cases follows.

The first line of each test case contains a single integer $n$ ($2 \le n \le 5000$) — the number of vertices in the tree.

The second line of each test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le 10^9$) — the values initially written on the vertices.

The third line of each test case contains $n - 1$ integers $p_2, p_3 , \ldots, p_n$ ($1 \le p_i < i$), indicating that there is an edge from vertex $p_i$ to vertex $i$. It is guaranteed that the given edges form a tree.

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

Output: For each test case, output a single integer — the minimum number of operations needed to make the tree wonderful.

Examples:
input:
4
5
9 3 4 1 2
1 1 3 3
2
5 3
1
2
36 54
1
3
0 0 0
1 2
output:
3
2
0
0

Note: The tree in the first test case:

![](CDN_BASE_URL/9a07d26506b9ad6c01c4152da8319590)

You can apply the operation once on vertex $5$ and twice on vertex $2$ to get a wonderful tree.

In the second test case, you can apply the operation twice on vertex $2$ to get a wonderful tree.

In the third and fourth test cases, the tree is already wonderful, so you don't need to apply any operations.

Buggy Code:
import java.io.*;
import java.util.*;
import java.math.*;

public class E {
	public static void main(String[] args) throws IOException {

		/**/
		Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
		/*/
		Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(new FileInputStream("src/e.in"))));
		/**/

		int t = sc.nextInt();
        for (int z = 0; z < t; ++z) {
            int n = sc.nextInt();
            int[] a = new int[n];
            int[] p = new int[n];
            long[] wonder = new long[n];
            int[] d = new int[n];
            for (int i = 0; i < n; ++i) {
                a[i] = sc.nextInt();
            }
            p[0] = -1;
            for (int i = 0; i < n-1; ++i) {
                p[i+1] = sc.nextInt()-1;
            }
            ArrayList<ArrayList<Integer>> ch = new ArrayList<>();
            for (int i = 0; i < n; ++i)
                ch.add(new ArrayList<>());
            for (int i = 1; i < n; ++i) {
                ch.get(p[i]).add(i);
            }
            ArrayDeque<Integer> q = new ArrayDeque<>();
            q.add(0);
            while (!q.isEmpty()) {
                int u = q.removeFirst();
                if (ch.get(u).isEmpty()) {
                    wonder[u] = 1234567890123456L;
                }
                for (int v : ch.get(u)) {
                    wonder[u] += a[v];
                    d[v] = d[u]+1;
                    q.add(v);
                }
                wonder[u] -= a[u];
            }
            q.add(0);
            ArrayDeque<Integer> q2 = new ArrayDeque<>();
            long ans = 0;
            while (!q.isEmpty()) {
                int u = q.removeFirst();
                if (wonder[u]>=0)
                    continue;
                q2.add(u);
                for (int v : ch.get(u)) {
                    q.add(v);
                }
                while (!q2.isEmpty()) {
                    int u2 = q2.removeFirst();
                    if (wonder[u]>=0) {
                        q2.clear();
                        break;
                    }
                    if (wonder[u2]>=0) {
                        long sub = Math.min(-wonder[u], wonder[u2]);
                        wonder[u]+=sub;
                        wonder[u2]-=sub;
                        ans += sub*(d[u2]-d[u]);
                    }
                    for (int v2 : ch.get(u2)) {
                        q2.add(v2);
                    }
                }
            }

            System.out.println(ans);
        }
	}
}

**Instructions:**
- Focus on edge cases or scenarios that maximize the failure probability in faulty solutions.
- Due to the output length limit, you should generate a **small-scale** test input that is **complete and valid**.
- Output the test input directly, not code to generate it.

**Output format:**
```plaintext
{test input}
```

Think step by step.

Response:
To generate a challenging test input that exposes the bug in the provided code, we need to consider edge cases or scenarios that maximize the failure probability in faulty solutions. Here are the steps to think through this:

1. **Understanding the Bug**: The provided code seems to have issues with how it calculates the `wonder` values and how it propagates the necessary operations to make the tree wonderful. Specifically, it might not correctly handle cases where the root or a parent node has a value that is significantly less than the sum of its children.

2. **Edge Cases**:
   - **Single Child**: A vertex with a single child where the parent's value is significantly less than the child's value.
   - **Multiple Children**: A vertex with multiple children where the sum of the children's values is much larger than the parent's value.
   - **Deep Tree**: A tree with a deep structure where the values at each level are significantly different.
   - **Zero Values**: A tree where some or all vertices have zero values.

3. **Constructing the Test Input**:
   - **Single Child Case**: Create a tree with a root and a single child where the root's value is much less than the child's value.
   - **Multiple Children Case**: Create a tree with a root and multiple children where the sum of the children's values is much larger than the root's value.
   - **Deep Tree Case**: Create a tree with a deep structure where the values at each level are significantly different.
   - **Zero Values Case**: Create a tree where some or all vertices have zero values.

Let's construct a test input that includes these cases:

```plaintext
4
2
1 10
1
3
1 10 10
1 1
5
1 10 10 10 10
1 1 1 1
3
0 0 0
1 2
```

### Explanation of the Test Input:

1. **Test Case 1**:
   - **Tree Structure**: Root (1) has a single child (2).
   - **Values**: `a = [1, 10]`, `p = [1]`.
   - **Expected Output**: 9 (The root needs to be increased by 9 to become 10, which is equal to the child's value).

2. **Test Case 2**:
   - **Tree Structure**: Root (1) has two children (2, 3).
   - **Values**: `a = [1, 10, 10]`, `p = [1, 1]`.
   - **Expected Output**: 19 (The root needs to be increased by 19 to become 20, which is equal to the sum of the children's values).

3. **Test Case 3**:
   - **Tree Structure**: Root (1) has four children (2, 3, 4, 5).
   - **Values**: `a = [1, 10, 10, 10, 10]`, `p = [1, 1, 1, 1]`.
   - **Expected Output**: 39 (The root needs to be increased by 39 to become 40, which is equal to the sum of the children's values).

4. **Test Case 4**:
   - **Tree Structure**: Root (1) has two children (2, 3).
   - **Values**: `a = [0, 0, 0]`, `p = [1, 2]`.
   - **Expected Output**: 0 (The tree is already wonderful since all values are zero).

This test input should help expose the bug in the provided code by covering various edge cases and scenarios.


**Task:**
Generate a challenging test input that exposes the bug in the buggy code of the algorithm problem:
Algorithm Problem:
Title: Wonderful Tree!
time_limit_ms: 2000
memory_limit_mb: 256
Description: God's Blessing on This ArrayForces!

A Random Pebble

You are given a tree with $n$ vertices, rooted at vertex $1$. The $i$-th vertex has an integer $a_i$ written on it.

Let $L$ be the set of all direct children$^{\text{∗}}$ of $v$. A tree is called wonderful, if for all vertices $v$ where $L$ is not empty, $$a_v \le \sum_{u \in L}{a_u}.$$ In one operation, you choose any vertex $v$ and increase $a_v$ by $1$.

Find the minimum number of operations needed to make the given tree wonderful!

$^{\text{∗}}$ Vertex $u$ is called a direct child of vertex $v$ if:

  * $u$ and $v$ are connected by an edge, and    * $v$ is on the (unique) path from $u$ to the root of the tree.

Input: Each test contains multiple test cases. The first line of input contains a single integer $t$ ($1 \le t \le 1000$) — the number of test cases. The description of the test cases follows.

The first line of each test case contains a single integer $n$ ($2 \le n \le 5000$) — the number of vertices in the tree.

The second line of each test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le 10^9$) — the values initially written on the vertices.

The third line of each test case contains $n - 1$ integers $p_2, p_3 , \ldots, p_n$ ($1 \le p_i < i$), indicating that there is an edge from vertex $p_i$ to vertex $i$. It is guaranteed that the given edges form a tree.

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

Output: For each test case, output a single integer — the minimum number of operations needed to make the tree wonderful.

Examples:
input:
4
5
9 3 4 1 2
1 1 3 3
2
5 3
1
2
36 54
1
3
0 0 0
1 2
output:
3
2
0
0

Note: The tree in the first test case:

![](CDN_BASE_URL/9a07d26506b9ad6c01c4152da8319590)

You can apply the operation once on vertex $5$ and twice on vertex $2$ to get a wonderful tree.

In the second test case, you can apply the operation twice on vertex $2$ to get a wonderful tree.

In the third and fourth test cases, the tree is already wonderful, so you don't need to apply any operations.

Buggy Code:
#include<bits/stdc++.h>
typedef long long ll;
using namespace std;
const int N=5005;
int t,n,a[N],x,c,d[N],o[N];
ll ans;
struct edge
{
	int t,e,h;
}e[N];
struct heap
{
	int v,l,r,d;
	ll s;
}h[N<<3];
int merge(int x,int y)
{
	if(!x||!y)
	  return x|y;
	if(h[y].v<h[x].v)
	  swap(x,y);
	h[x].r=merge(h[x].r,y);
	if(h[h[x].l].d<h[h[x].r].d)
	  swap(h[x].l,h[x].r);
	h[x].d=h[h[x].r].d+1;
	return x;
}
void add(int u,int v)
{
	++c;
	e[c].t=v;
	e[c].e=e[u].h;
	e[u].h=c;
	return ;
}
void search(int p)
{
	int i;
	ll t=0;
	for(i=e[p].h;i;i=e[i].e)
	{
		d[e[i].t]=d[p]+1;
		search(e[i].t);
		if(!o[p])
		  o[p]=o[e[i].t];
		else
		  o[p]=merge(o[p],o[e[i].t]);
		t=t+a[e[i].t];
	}
	if(!e[p].h)
	{
		++c,o[p]=c;
		h[c].v=d[p];
		h[c].s=1e18;
		h[c].d=1;
		return ;
	}
	t=t-a[p];
	if(t>0)
	{
		++c,h[c].v=d[p],h[c].s=t,h[c].d=1;
		o[p]=merge(o[p],c);
		return ;
	}
	t=-t;
	while(t)
	{
		if(h[o[p]].s>=1e18)
		{
			ans=ans+t*(h[o[p]].v-d[p]);
			break;
		}
		if(h[o[p]].s<=t)
		{
			ans=ans+h[o[p]].s*(h[o[p]].v-d[p]);
			t=t-h[o[p]].s;
			o[p]=merge(h[o[p]].l,h[o[p]].r);
		}
		else
		{
			ans=ans+t*(h[o[p]].v-d[p]);
			t=0;
			h[o[p]].s-=t;
			break;
		}
	}
	return ;
}
int main()
{
	int i;
	scanf("%d",&t);
	while(t)
	{
		--t,ans=0,c=0;
		scanf("%d",&n);
		for(i=1;i<=n;++i)
		  o[i]=0,scanf("%d",&a[i]),e[i].h=0;
		for(i=2;i<=n;++i)
		  scanf("%d",&x),add(x,i);
		c=0,search(1);
		printf("%lld\n",ans);
	}
	return 0;
}

**Instructions:**
- Focus on edge cases or scenarios that maximize the failure probability in faulty solutions.
- Due to the output length limit, you should generate a **small-scale** test input that is **complete and valid**.
- Output the test input directly, not code to generate it.

**Output format:**
```plaintext
{test input}
```

Think step by step.

Response:
To expose the bug in the provided code, we need to focus on scenarios that might cause the code to fail, particularly in edge cases or complex tree structures. Here are some steps to generate a challenging test input:

1. **Simple Tree with a Root Node and Two Children**:
   - This can help test the basic functionality of the code.
   - Example: A tree with 3 nodes where the root has two children.

2. **Tree with a Long Chain**:
   - A tree where each node has only one child, forming a long chain.
   - This can test the code's ability to handle deep trees.

3. **Tree with a Heavy Root**:
   - A tree where the root node has a large value, and all its children have small values.
   - This can test the code's ability to handle large values and ensure the root's value is appropriately adjusted.

4. **Tree with a Heavy Child**:
   - A tree where one of the children has a large value, and the root has a small value.
   - This can test the code's ability to handle unbalanced trees.

5. **Tree with Multiple Levels and Complex Structure**:
   - A tree with multiple levels and a mix of heavy and light nodes.
   - This can test the code's ability to handle more complex tree structures.

Based on these considerations, let's generate a small-scale test input that is complete and valid:

```plaintext
3
3
10 5 5
1 1
4
10 1 1 1
1 1 1
6
1 10 1 10 1 10
1 2 2 3 3
```

### Explanation of the Test Cases:

1. **Test Case 1**:
   - Tree: 3 nodes, root at 1 with two children 2 and 3.
   - Values: 10, 5, 5.
   - Edges: 1-2, 1-3.
   - This tree is already wonderful, so no operations are needed.

2. **Test Case 2**:
   - Tree: 4 nodes, root at 1 with three children 2, 3, and 4.
   - Values: 10, 1, 1, 1.
   - Edges: 1-2, 1-3, 1-4.
   - The root value (10) is much larger than the sum of its children (3), so no operations are needed.

3. **Test Case 3**:
   - Tree: 6 nodes, root at 1 with a complex structure.
   - Values: 1, 10, 1, 10, 1, 10.
   - Edges: 1-2, 2-3, 2-4, 3-5, 3-6.
   - This tree has a mix of heavy and light nodes, which can challenge the code to handle unbalanced subtrees.

This test input should help expose any bugs in the provided code, particularly in handling complex tree structures and unbalanced node values.


**Task:**
Generate a challenging test input that exposes the bug in the buggy code of the algorithm problem:
Algorithm Problem:
Title: Wonderful Tree!
time_limit_ms: 2000
memory_limit_mb: 256
Description: God's Blessing on This ArrayForces!

A Random Pebble

You are given a tree with $n$ vertices, rooted at vertex $1$. The $i$-th vertex has an integer $a_i$ written on it.

Let $L$ be the set of all direct children$^{\text{∗}}$ of $v$. A tree is called wonderful, if for all vertices $v$ where $L$ is not empty, $$a_v \le \sum_{u \in L}{a_u}.$$ In one operation, you choose any vertex $v$ and increase $a_v$ by $1$.

Find the minimum number of operations needed to make the given tree wonderful!

$^{\text{∗}}$ Vertex $u$ is called a direct child of vertex $v$ if:

  * $u$ and $v$ are connected by an edge, and    * $v$ is on the (unique) path from $u$ to the root of the tree.

Input: Each test contains multiple test cases. The first line of input contains a single integer $t$ ($1 \le t \le 1000$) — the number of test cases. The description of the test cases follows.

The first line of each test case contains a single integer $n$ ($2 \le n \le 5000$) — the number of vertices in the tree.

The second line of each test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le 10^9$) — the values initially written on the vertices.

The third line of each test case contains $n - 1$ integers $p_2, p_3 , \ldots, p_n$ ($1 \le p_i < i$), indicating that there is an edge from vertex $p_i$ to vertex $i$. It is guaranteed that the given edges form a tree.

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

Output: For each test case, output a single integer — the minimum number of operations needed to make the tree wonderful.

Examples:
input:
4
5
9 3 4 1 2
1 1 3 3
2
5 3
1
2
36 54
1
3
0 0 0
1 2
output:
3
2
0
0

Note: The tree in the first test case:

![](CDN_BASE_URL/9a07d26506b9ad6c01c4152da8319590)

You can apply the operation once on vertex $5$ and twice on vertex $2$ to get a wonderful tree.

In the second test case, you can apply the operation twice on vertex $2$ to get a wonderful tree.

In the third and fourth test cases, the tree is already wonderful, so you don't need to apply any operations.

Buggy Code:
#include <bits/stdc++.h>
using namespace std;

const int N = 5010;
int n, m[N][N], t[N], a[N];
vector<int> c[N];

void d(int x) {
    if (c[x].empty()) {
        for (int i = 1; i <= n; ++i)
            m[x][i] = INT_MAX;
        t[x] = 0;
        return;
    }

    int s = 0;
    t[x] = 0;
    for (auto j : c[x]) {
        d(j);
        t[x] += t[j];
        s += a[j];
    }

    int l = a[x] - s;
    for (int i = 1; i <= n; ++i) {
        if (l <= 0) break;
        for (auto j : c[x]) {
            if (l <= 0) break;
            if (m[j][i] <= l) {
                t[x] += i * m[j][i];
                l -= m[j][i];
                m[j][i] = 0;
            } else {
                t[x] += i * l;
                m[j][i] -= l;
                l = 0;
            }
        }
    }

    if (l < 0) m[x][1] = -l;
    for (int i = 2; i <= n; ++i) {
        int o = 0;
        for (auto j : c[x]) {
            if (m[j][i - 1] == INT_MAX) {
                o = INT_MAX;
                break;
            }
            o += m[j][i - 1];
        }
        m[x][i] = o;
    }
}

int main() {
#ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
#endif
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);

    int T;
    cin >> T;
    while (T--) {
        cin >> n;
        for (int i = 1; i <= n; ++i) {
            cin >> a[i];
            c[i].clear();
        }

        for (int i = 2; i <= n; ++i) {
            int p;
            cin >> p;
            c[p].push_back(i);
        }

        d(1);
        cout << t[1] << "\n";
    }

    return 0;
}

**Instructions:**
- Focus on edge cases or scenarios that maximize the failure probability in faulty solutions.
- Due to the output length limit, you should generate a **small-scale** test input that is **complete and valid**.
- Output the test input directly, not code to generate it.

**Output format:**
```plaintext
{test input}
```

Think step by step.

Response:
```plaintext
1
5
1 1 1 1 1
1 1 2 2
```

**Explanation:**

This test case is designed to challenge the given buggy code by providing a tree where the root node and its direct children have the same value, and the grandchildren also have the same value. The tree structure is as follows:

- Root node (1) with value 1
- Two direct children (2 and 3) of the root, each with value 1
- Two grandchildren (4 and 5) of node 2, each with value 1

To make this tree wonderful, the value of the root node (1) needs to be increased to at least the sum of the values of its direct children (2 + 1 = 3). Similarly, the value of node 2 needs to be increased to at least the sum of the values of its direct children (1 + 1 = 2).

The correct output for this test case should be 3, as you need to:
- Increase the value of node 1 by 2 (to 3)
- Increase the value of node 2 by 1 (to 2)

This test case exposes the bug in the buggy code, which might not correctly handle the propagation of the required operations from the root node to its children and grandchildren.


**Task:**
Generate a challenging test input that exposes the bug in the buggy code of the algorithm problem:
Algorithm Problem:
Title: Wonderful Tree!
time_limit_ms: 2000
memory_limit_mb: 256
Description: God's Blessing on This ArrayForces!

A Random Pebble

You are given a tree with $n$ vertices, rooted at vertex $1$. The $i$-th vertex has an integer $a_i$ written on it.

Let $L$ be the set of all direct children$^{\text{∗}}$ of $v$. A tree is called wonderful, if for all vertices $v$ where $L$ is not empty, $$a_v \le \sum_{u \in L}{a_u}.$$ In one operation, you choose any vertex $v$ and increase $a_v$ by $1$.

Find the minimum number of operations needed to make the given tree wonderful!

$^{\text{∗}}$ Vertex $u$ is called a direct child of vertex $v$ if:

  * $u$ and $v$ are connected by an edge, and    * $v$ is on the (unique) path from $u$ to the root of the tree.

Input: Each test contains multiple test cases. The first line of input contains a single integer $t$ ($1 \le t \le 1000$) — the number of test cases. The description of the test cases follows.

The first line of each test case contains a single integer $n$ ($2 \le n \le 5000$) — the number of vertices in the tree.

The second line of each test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le 10^9$) — the values initially written on the vertices.

The third line of each test case contains $n - 1$ integers $p_2, p_3 , \ldots, p_n$ ($1 \le p_i < i$), indicating that there is an edge from vertex $p_i$ to vertex $i$. It is guaranteed that the given edges form a tree.

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

Output: For each test case, output a single integer — the minimum number of operations needed to make the tree wonderful.

Examples:
input:
4
5
9 3 4 1 2
1 1 3 3
2
5 3
1
2
36 54
1
3
0 0 0
1 2
output:
3
2
0
0

Note: The tree in the first test case:

![](CDN_BASE_URL/9a07d26506b9ad6c01c4152da8319590)

You can apply the operation once on vertex $5$ and twice on vertex $2$ to get a wonderful tree.

In the second test case, you can apply the operation twice on vertex $2$ to get a wonderful tree.

In the third and fourth test cases, the tree is already wonderful, so you don't need to apply any operations.

Buggy Code:
import sys, os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def make_graph(n, m):
    x, s = [0] * (2 * m), [0] * (n + 3)
    for i in range(0, 2 * m, 2):
        u, v = p[i >> 1], (i >> 1) + 2
        s[u + 2] += 1
        x[i], x[i + 1] = u, v
    for i in range(3, n + 3):
        s[i] += s[i - 1]
    G = [0] * m
    for i in range(0, 2 * m, 2):
        j = x[i] + 1
        G[s[j]] = x[i ^ 1]
        s[j] += 1
    return G, s

t = int(input())
ans = []
inf = pow(10, 15) + 1
for _ in range(t):
    n = int(input())
    a = [0] + list(map(int, input().split()))
    p = list(map(int, input().split()))
    G, s0 = make_graph(n, n - 1)
    dp = [0] * (n + 1)
    dist = [0] * (n + 1)
    for i in range(1, n + 1):
        u, di = a[i], dist[i]
        for v in range(s0[i], s0[i + 1]):
            j = G[v]
            u -= a[j]
            dist[j] = di + 1
        dp[i] = u if s0[i] ^ s0[i + 1] else -inf
    ans0 = 0
    for i in range(n, 0, -1):
        if dp[i] <= 0:
            continue
        q, di = [i], dist[i]
        for j in q:
            for v in range(s0[j], s0[j + 1]):
                k = G[v]
                if dp[k] >= 0:
                    continue
                c = min(-dp[k], dp[i])
                dp[i] -= c
                dp[k] += c
                ans0 += (dist[k] - di) * c
                if dp[i] <= 0:
                    break
                q.append(k)
            if dp[i] <= 0:
                break
    ans.append(ans0)
sys.stdout.write("\n".join(map(str, ans)))

**Instructions:**
- Focus on edge cases or scenarios that maximize the failure probability in faulty solutions.
- Due to the output length limit, you should generate a **small-scale** test input that is **complete and valid**.
- Output the test input directly, not code to generate it.

**Output format:**
```plaintext
{test input}
```

Think step by step.

Response:
```plaintext
1
5
1 2 3 4 5
1 1 1 1
```

**Explanation:**

This test case is designed to expose potential issues in the buggy code by creating a tree where the root node has a very low value, and all its children have higher values. The tree structure is as follows:

- Vertex 1 (root) has a value of 1.
- Vertex 2, 3, 4, and 5 are all direct children of Vertex 1, with values 2, 3, 4, and 5 respectively.

For the tree to be wonderful, the value at the root (Vertex 1) must be at least the sum of the values of its children. Therefore, the minimum number of operations needed is:

\[ 1 + 2 + 3 + 4 + 5 - 1 = 14 \]

The correct output for this test case should be 14. This test case is small and valid, and it should help identify issues in the faulty solution.


**Task:**
Generate a challenging test input that exposes the bug in the buggy code of the algorithm problem:
Algorithm Problem:
Title: Wonderful Tree!
time_limit_ms: 2000
memory_limit_mb: 256
Description: God's Blessing on This ArrayForces!

A Random Pebble

You are given a tree with $n$ vertices, rooted at vertex $1$. The $i$-th vertex has an integer $a_i$ written on it.

Let $L$ be the set of all direct children$^{\text{∗}}$ of $v$. A tree is called wonderful, if for all vertices $v$ where $L$ is not empty, $$a_v \le \sum_{u \in L}{a_u}.$$ In one operation, you choose any vertex $v$ and increase $a_v$ by $1$.

Find the minimum number of operations needed to make the given tree wonderful!

$^{\text{∗}}$ Vertex $u$ is called a direct child of vertex $v$ if:

  * $u$ and $v$ are connected by an edge, and    * $v$ is on the (unique) path from $u$ to the root of the tree.

Input: Each test contains multiple test cases. The first line of input contains a single integer $t$ ($1 \le t \le 1000$) — the number of test cases. The description of the test cases follows.

The first line of each test case contains a single integer $n$ ($2 \le n \le 5000$) — the number of vertices in the tree.

The second line of each test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le 10^9$) — the values initially written on the vertices.

The third line of each test case contains $n - 1$ integers $p_2, p_3 , \ldots, p_n$ ($1 \le p_i < i$), indicating that there is an edge from vertex $p_i$ to vertex $i$. It is guaranteed that the given edges form a tree.

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

Output: For each test case, output a single integer — the minimum number of operations needed to make the tree wonderful.

Examples:
input:
4
5
9 3 4 1 2
1 1 3 3
2
5 3
1
2
36 54
1
3
0 0 0
1 2
output:
3
2
0
0

Note: The tree in the first test case:

![](CDN_BASE_URL/9a07d26506b9ad6c01c4152da8319590)

You can apply the operation once on vertex $5$ and twice on vertex $2$ to get a wonderful tree.

In the second test case, you can apply the operation twice on vertex $2$ to get a wonderful tree.

In the third and fourth test cases, the tree is already wonderful, so you don't need to apply any operations.

Buggy Code:
import sys
input = lambda: sys.stdin.readline().strip()
from collections import deque

class segtree():
    n=1
    size=1
    log=2
    d=[0]
    op=None
    e=10**15
    def __init__(self,V,OP,E):
        self.n=len(V)
        self.op=OP
        self.e=E
        self.log=(self.n-1).bit_length()
        self.size=1<<self.log
        self.d=[E for i in range(2*self.size)]
        for i in range(self.n):
            self.d[self.size+i]=V[i]
        for i in range(self.size-1,0,-1):
            self.update(i)
    def set(self,p,x):
        assert 0<=p and p<self.n
        p+=self.size
        self.d[p]=x
        for i in range(1,self.log+1):
            self.update(p>>i)
    def get(self,p):
        assert 0<=p and p<self.n
        return self.d[p+self.size]
    def prod(self,l,r):
        assert 0<=l and l<=r and r<=self.n
        sml=self.e
        smr=self.e
        l+=self.size
        r+=self.size
        while(l<r):
            if (l&1):
                sml=self.op(sml,self.d[l])
                l+=1
            if (r&1):
                smr=self.op(self.d[r-1],smr)
                r-=1
            l>>=1
            r>>=1
        return self.op(sml,smr)
    def all_prod(self):
        return self.d[1]
    def max_right(self,l,f):
        assert 0<=l and l<=self.n
        assert f(self.e)
        if l==self.n:
            return self.n
        l+=self.size
        sm=self.e
        while(1):
            while(l%2==0):
                l>>=1
            if not(f(self.op(sm,self.d[l]))):
                while(l<self.size):
                    l=2*l
                    if f(self.op(sm,self.d[l])):
                        sm=self.op(sm,self.d[l])
                        l+=1
                return l-self.size
            sm=self.op(sm,self.d[l])
            l+=1
            if (l&-l)==l:
                break
        return self.n
    def min_left(self,r,f):
        assert 0<=r and r<=self.n
        assert f(self.e)
        if r==0:
            return 0
        r+=self.size
        sm=self.e
        while(1):
            r-=1
            while(r>1 and (r%2)):
                r>>=1
            if not(f(self.op(self.d[r],sm))):
                while(r<self.size):
                    r=(2*r+1)
                    if f(self.op(self.d[r],sm)):
                        sm=self.op(self.d[r],sm)
                        r-=1
                return r+1-self.size
            sm=self.op(self.d[r],sm)
            if (r& -r)==r:
                break
        return 0
    def update(self,k):
        self.d[k]=self.op(self.d[2*k],self.d[2*k+1])
    def __str__(self):
        return str([self.get(i) for i in range(self.n)])

def add(x,y):
  return x + y

def Map():
  return list(map(int,input().split()))

for _ in range(int(input())):
  n = int(input())
  a = Map()
  p = Map()

  G = [[] for i in range(n)]
  for i in range(n-1):
    u = i + 1
    p[i] -= 1
    G[p[i]].append(u)

  depth = [n+1 for i in range(n)]
  depth[0] = 0
  sub = [1] * n
  todo = [0,0]
  visit = []
  t = 0
  In = [-1] * n
  Out = [0] * n
  B = []
  while len(todo):
    u = todo.pop()
    visit.append(u)
    if In[u] != -1:
      Out[u] = t
      B.append(0)
      t += 1
      continue
    In[u] = t
    t += 1
    B.append(a[u])
    for v in G[u]:
      depth[v] = depth[u] + 1
      todo.append(v)
      todo.append(v)

  for i in range(n-1,-1,-1):
    v = visit[i]
    for u in G[v]:
      sub[v] += sub[u]

  for i in range(2*n-1,0,-1):
    B[i] -= B[i-1]

  seg = segtree(B,add,0)
  ans = 0
  for r in range(n):
    if sub[r] == 1:
      continue
    s = seg.prod(0,In[r]+1) - seg.prod(0,Out[r]+1)
    for v in G[r]:
      s -= seg.prod(0,In[v]+1) - seg.prod(0,Out[v]+1)
    if s <= 0:
      continue
    todo = deque([r])
    while len(todo):
      u = todo.popleft()
      ss = seg.prod(0,In[u]+1) - seg.prod(0,Out[u]+1)
      ss = -ss
      for v in G[u]:
        todo.append(v)
        ss += seg.prod(0,In[v]+1) - seg.prod(0,Out[v]+1)
      if u == r:
        continue
      if sub[u] == 1:
        ss = 10 ** 18
      if ss <= 0:
        continue
      c = min(s,ss)
      ans += (depth[u] - depth[r]) * c
      s -= c
      seg.set(In[r] + 1,seg.get(In[r] + 1)+c)
      seg.set(In[u] + 1,seg.get(In[u] + 1)-c)
  print(ans)

**Instructions:**
- Focus on edge cases or scenarios that maximize the failure probability in faulty solutions.
- Due to the output length limit, you should generate a **small-scale** test input that is **complete and valid**.
- Output the test input directly, not code to generate it.

**Output format:**
```plaintext
{test input}
```

Think step by step.

Response:
```plaintext
3
4
1 1 1 1
1 2 3
3
1 2 3
1 2
2
10 20
1
```


**Task:**
Generate a challenging test input that exposes the bug in the buggy code of the algorithm problem:
Algorithm Problem:
Title: Wonderful Tree!
time_limit_ms: 2000
memory_limit_mb: 256
Description: God's Blessing on This ArrayForces!

A Random Pebble

You are given a tree with $n$ vertices, rooted at vertex $1$. The $i$-th vertex has an integer $a_i$ written on it.

Let $L$ be the set of all direct children$^{\text{∗}}$ of $v$. A tree is called wonderful, if for all vertices $v$ where $L$ is not empty, $$a_v \le \sum_{u \in L}{a_u}.$$ In one operation, you choose any vertex $v$ and increase $a_v$ by $1$.

Find the minimum number of operations needed to make the given tree wonderful!

$^{\text{∗}}$ Vertex $u$ is called a direct child of vertex $v$ if:

  * $u$ and $v$ are connected by an edge, and    * $v$ is on the (unique) path from $u$ to the root of the tree.

Input: Each test contains multiple test cases. The first line of input contains a single integer $t$ ($1 \le t \le 1000$) — the number of test cases. The description of the test cases follows.

The first line of each test case contains a single integer $n$ ($2 \le n \le 5000$) — the number of vertices in the tree.

The second line of each test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le 10^9$) — the values initially written on the vertices.

The third line of each test case contains $n - 1$ integers $p_2, p_3 , \ldots, p_n$ ($1 \le p_i < i$), indicating that there is an edge from vertex $p_i$ to vertex $i$. It is guaranteed that the given edges form a tree.

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

Output: For each test case, output a single integer — the minimum number of operations needed to make the tree wonderful.

Examples:
input:
4
5
9 3 4 1 2
1 1 3 3
2
5 3
1
2
36 54
1
3
0 0 0
1 2
output:
3
2
0
0

Note: The tree in the first test case:

![](CDN_BASE_URL/9a07d26506b9ad6c01c4152da8319590)

You can apply the operation once on vertex $5$ and twice on vertex $2$ to get a wonderful tree.

In the second test case, you can apply the operation twice on vertex $2$ to get a wonderful tree.

In the third and fourth test cases, the tree is already wonderful, so you don't need to apply any operations.

Buggy Code:
import java.util.*;
import java.io.*;

public class Main {
    static PrintWriter pw = new PrintWriter(System.out);
    static Scanner sc = new Scanner(System.in);
    static ArrayList<Integer> adjl [];
    static int deg [];
    static boolean vis [];

    public static void bfs(int j){
        deg[j] = 1;
        Queue<Integer> qu = new LinkedList<>();
        qu.add(j);
        vis[j] = true;
        while(!qu.isEmpty()){
            j = qu.poll();
            for(int i = 0; i < adjl[j].size() ; i++){
                if(!vis[adjl[j].get(i)]){
                    qu.add(adjl[j].get(i));
                    vis[adjl[j].get(i)] = true;
                    deg[adjl[j].get(i)] = deg[j] + 1;
                }
            }
        }
    }

    public static void solve() throws IOException {
        int n = sc.nextInt();
        int a [] = new int [n + 1];
        for(int i = 1; i <= n ; i++)
            a[i] = sc.nextInt();
        int b [] = new int [n + 1];
        deg = new int [n + 1];
        vis = new boolean[n + 1];
        adjl = new ArrayList [n + 1];
        for(int i = 0; i <= n ; i++)
            adjl[i] = new ArrayList<>();
        for(int i = 0; i < n - 1 ; i++){
            int u = sc.nextInt();
            int v = i + 2;
            adjl[u].add(v);
            adjl[v].add(u);
        }
        bfs(1);
        Arrays.fill(vis, false);
        int leaves = 0;
        for(int i : deg)
            leaves = Math.max(leaves, i);
        ArrayList<Integer> list []  = new ArrayList [leaves + 1];
        for(int i = 1 ; i <= leaves ; i++)
            list[i] = new ArrayList<>();
        for(int i = 1 ; i <= leaves ; i++)
            list[deg[i]].add(i);
        long ans = 0;
        for(int i = leaves ; i >= 1; i--){
            for(int j = 0; j < list[i].size() ; j++) {
                int cnt = 0;
                for (int k = 0; k < adjl[list[i].get(j)].size(); k++) {
                    if (deg[adjl[list[i].get(j)].get(k)] > i) {
                        cnt += a[adjl[list[i].get(j)].get(k)];
                    }
                }
                if(cnt >= a[list[i].get(j)]) {
                    b[list[i].get(j)] = cnt - a[list[i].get(j)];
//                    pw.println(Arrays.toString(b));
                }
                else{
                    int diff = a[list[i].get(j)] - cnt;
                    Queue<Integer> qu = new LinkedList<>();
                    qu.add(list[i].get(j));
                    int mx = Integer.MAX_VALUE;
                    while (!qu.isEmpty()){
                        int idx = qu.poll();
                        if(adjl[idx].size() == 1 && idx != 1)
                            mx = Math.min(mx, deg[idx]);
                        for(int k = 0; k < adjl[idx].size() ; k++){
                            if(deg[adjl[idx].get(k)] > deg[idx]){
                                qu.add(adjl[idx].get(k));
                            }
                        }
                    }
                    qu.clear();
                    qu.add(list[i].get(j));
                    while (!qu.isEmpty()){
                        int idx = qu.poll();
                        for(int k = 0; k < adjl[idx].size() ; k++){
                            if(deg[adjl[idx].get(k)] > deg[idx]){
                                if(b[adjl[idx].get(k)] > 0 && deg[adjl[idx].get(k)] - deg[list[i].get(j)] < mx){
                                    if(diff > b[adjl[idx].get(k)]){
                                        diff -= b[adjl[idx].get(k)];
                                        ans += b[adjl[idx].get(k)] * (deg[adjl[idx].get(k)] - deg[list[i].get(j)]);
                                        b[adjl[idx].get(k)] = 0;
                                    }
                                    else{
                                        ans += diff * (deg[adjl[idx].get(k)] - deg[list[i].get(j)]);
                                        b[adjl[idx].get(k)] -= diff;
                                        diff = 0;
                                    }
                                }
                                qu.add(adjl[idx].get(k));
                            }
                        }
                    }
                    if(diff > 0){
                        ans += diff * (mx -  deg[list[i].get(j)]);
                    }
                }
            }
        }
//        pw.println(Arrays.toString(b));
        pw.println(ans);
    }

    public static void main(String[] args) throws IOException{
        int t = sc.nextInt();
        while(t -- > 0)
            solve();
        pw.flush();
    }

    static class Scanner {
        StringTokenizer st;
        BufferedReader br;

        public Scanner(InputStream s) {
            br = new BufferedReader(new InputStreamReader(s));
        }

        public Scanner(String s) throws FileNotFoundException {
            br = new BufferedReader(new FileReader(s));
        }

        public String next() throws IOException {
            while (st == null || !st.hasMoreTokens())
                st = new StringTokenizer(br.readLine());
            return st.nextToken();
        }

        public int nextInt() throws IOException {
            return Integer.parseInt(next());
        }

        public long nextLong() throws IOException {
            return Long.parseLong(next());
        }

        public String nextLine() throws IOException {
            return br.readLine();
        }

        public double nextDouble() throws IOException {
            String x = next();
            StringBuilder sb = new StringBuilder("0");
            double res = 0, f = 1;
            boolean dec = false, neg = false;
            int start = 0;
            if (x.charAt(0) == '-') {
                neg = true;
                start++;
            }
            for (int i = start; i < x.length(); i++)
                if (x.charAt(i) == '.') {
                    res = Long.parseLong(sb.toString());
                    sb = new StringBuilder("0");
                    dec = true;
                } else {
                    sb.append(x.charAt(i));
                    if (dec)
                        f *= 10;
                }
            res += Long.parseLong(sb.toString()) / f;
            return res * (neg ? -1 : 1);
        }

        public long[] nextlongArray(int n) throws IOException {
            long[] a = new long[n];
            for (int i = 0; i < n; i++)
                a[i] = nextLong();
            return a;
        }

        public Long[] nextLongArray(int n) throws IOException {
            Long[] a = new Long[n];
            for (int i = 0; i < n; i++)
                a[i] = nextLong();
            return a;
        }

        public int[] nextIntArray(int n) throws IOException {
            int[] a = new int[n];
            for (int i = 0; i < n; i++)
                a[i] = nextInt();
            return a;
        }

        public Integer[] nextIntegerArray(int n) throws IOException {
            Integer[] a = new Integer[n];
            for (int i = 0; i < n; i++)
                a[i] = nextInt();
            return a;
        }

        public boolean ready() throws IOException {
            return br.ready();
        }
    }
}

**Instructions:**
- Focus on edge cases or scenarios that maximize the failure probability in faulty solutions.
- Due to the output length limit, you should generate a **small-scale** test input that is **complete and valid**.
- Output the test input directly, not code to generate it.

**Output format:**
```plaintext
{test input}
```

Think step by step.

Response:
To generate a challenging test input that exposes the bug in the provided code, we need to consider edge cases and scenarios that maximize the failure probability. The code is supposed to make the tree wonderful by ensuring that for every vertex \( v \), the sum of the values of its children is greater than or equal to the value of \( v \).

### Step-by-Step Analysis:
1. **Edge Cases:**
   - **Single Child:** A vertex with only one child.
   - **Multiple Children:** A vertex with multiple children.
   - **Leaves:** Vertices with no children.
   - **Deep Trees:** Trees with a large depth.
   - **Balanced Trees:** Trees where the values are evenly distributed.
   - **Unbalanced Trees:** Trees where the values are highly unbalanced.

2. **Challenging Scenarios:**
   - **Vertices with high values and low-value children:** This can cause the code to fail if it doesn't correctly handle the distribution of operations.
   - **Vertices with low values and high-value children:** This can cause the code to fail if it doesn't correctly handle the redistribution of values.
   - **Complex Tree Structures:** Trees with complex structures, such as long chains or deep subtrees, can expose bugs in the BFS and DFS logic.

### Challenging Test Input:
Let's create a test input that includes a vertex with a high value and low-value children, and a vertex with low values and high-value children. This will test the code's ability to handle such imbalances.

```plaintext
1
5
9 3 4 1 2
1 1 3 3
```

### Explanation:
- **Tree Structure:**
  - Vertex 1 has children 2 and 3.
  - Vertex 3 has children 4 and 5.
- **Values:**
  - Vertex 1: 9
  - Vertex 2: 3
  - Vertex 3: 4
  - Vertex 4: 1
  - Vertex 5: 2

### Expected Output:
- **Operations Needed:**
  - For vertex 1: \( a_1 \le a_2 + a_3 \) (9 <= 3 + 4) is false. Increase \( a_1 \) by 2.
  - For vertex 3: \( a_3 \le a_4 + a_5 \) (4 <= 1 + 2) is false. Increase \( a_3 \) by 1.
  - For vertex 4 and 5: No children, so no operations needed.

Total operations needed: 3

This test input is small and complete, and it should expose the bug in the code if the logic for handling imbalances in vertex values is incorrect.


**Task:**
Generate a challenging test input that exposes the bug in the buggy code of the algorithm problem:
Algorithm Problem:
Title: Wonderful Tree!
time_limit_ms: 2000
memory_limit_mb: 256
Description: God's Blessing on This ArrayForces!

A Random Pebble

You are given a tree with $n$ vertices, rooted at vertex $1$. The $i$-th vertex has an integer $a_i$ written on it.

Let $L$ be the set of all direct children$^{\text{∗}}$ of $v$. A tree is called wonderful, if for all vertices $v$ where $L$ is not empty, $$a_v \le \sum_{u \in L}{a_u}.$$ In one operation, you choose any vertex $v$ and increase $a_v$ by $1$.

Find the minimum number of operations needed to make the given tree wonderful!

$^{\text{∗}}$ Vertex $u$ is called a direct child of vertex $v$ if:

  * $u$ and $v$ are connected by an edge, and    * $v$ is on the (unique) path from $u$ to the root of the tree.

Input: Each test contains multiple test cases. The first line of input contains a single integer $t$ ($1 \le t \le 1000$) — the number of test cases. The description of the test cases follows.

The first line of each test case contains a single integer $n$ ($2 \le n \le 5000$) — the number of vertices in the tree.

The second line of each test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le 10^9$) — the values initially written on the vertices.

The third line of each test case contains $n - 1$ integers $p_2, p_3 , \ldots, p_n$ ($1 \le p_i < i$), indicating that there is an edge from vertex $p_i$ to vertex $i$. It is guaranteed that the given edges form a tree.

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

Output: For each test case, output a single integer — the minimum number of operations needed to make the tree wonderful.

Examples:
input:
4
5
9 3 4 1 2
1 1 3 3
2
5 3
1
2
36 54
1
3
0 0 0
1 2
output:
3
2
0
0

Note: The tree in the first test case:

![](CDN_BASE_URL/9a07d26506b9ad6c01c4152da8319590)

You can apply the operation once on vertex $5$ and twice on vertex $2$ to get a wonderful tree.

In the second test case, you can apply the operation twice on vertex $2$ to get a wonderful tree.

In the third and fourth test cases, the tree is already wonderful, so you don't need to apply any operations.

Buggy Code:
import java.util.*;
import java.io.*;
public class E {
  public static void main(String[] args) throws IOException {
    BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
		PrintWriter pw = new PrintWriter(System.out);

    StringTokenizer st = new StringTokenizer(r.readLine());
    int T = Integer.parseInt(st.nextToken());
    for(int z = 0; z < T; z++) {
      st = new StringTokenizer(r.readLine());
      int n = Integer.parseInt(st.nextToken());
      st = new StringTokenizer(r.readLine());
      long[] value = new long[n];
      for(int j = 0; j < n; j++) {
        value[j] = Long.parseLong(st.nextToken());
      }
      ArrayList<ArrayList<Integer>> children = new ArrayList<ArrayList<Integer>>();
      for(int i = 0; i < n; i++) {
        children.add(new ArrayList<Integer>());
      }
      ArrayList<ArrayList<Integer>> edges = new ArrayList<ArrayList<Integer>>();
      for(int i = 0; i < n; i++) {
        edges.add(new ArrayList<Integer>());
      }
      st = new StringTokenizer(r.readLine());
      for(int i = 1; i < n; i++) {
        int v = Integer.parseInt(st.nextToken()) - 1;
        edges.get(i).add(v);
        edges.get(v).add(i);
      }
      boolean[] visited = new boolean[n];
      int[] parent = new int[n];
      ArrayList<Integer> nodes = new ArrayList<Integer>();
      nodes.add(0);
      visited[0] = true;
      int index = 0;
      while(index < nodes.size()) {
        int current = nodes.get(index);
        for(int i = 0; i < edges.get(current).size(); i++) {
          if(!visited[edges.get(current).get(i)]) {
            visited[edges.get(current).get(i)] = true;
            nodes.add(edges.get(current).get(i));
            children.get(current).add(edges.get(current).get(i));
            parent[edges.get(current).get(i)] = current;
          }
        }
        index++;
      }
      nodes.clear();
      int[] chain = new int[n];
      for(int i = 0; i < n; i++) {
        if(children.get(i).size() == 0) {
          nodes.add(i);
        }
      }
      int index2 = 0;
      while(index2 < nodes.size()) {
        int c = nodes.get(index2);
        int p = parent[c];
        if(c != 0) {
          if(chain[p] == 0) {
            chain[p] = chain[c] + 1;
            nodes.add(p);
          } else {
            chain[p] = Math.min(chain[p], chain[c] + 1);
          }
        }
        index2++;
      }
      long ans = 0l;
      for(int i = 0; i < n; i++) {
        long sum = 0l;
        for(int j = 0; j < children.get(i).size(); j++) {
          sum += value[children.get(i).get(j)];
        }
        ans += Math.max(0, (value[i] - sum)*chain[i]);
      }
      pw.println(ans);
    }
    pw.close();
  }
}

**Instructions:**
- Focus on edge cases or scenarios that maximize the failure probability in faulty solutions.
- Due to the output length limit, you should generate a **small-scale** test input that is **complete and valid**.
- Output the test input directly, not code to generate it.

**Output format:**
```plaintext
{test input}
```

Think step by step.

Response:
To create a challenging test input that exposes the bug in the provided buggy code, we need to consider the following aspects:

1. **Edge Cases**: Test cases with minimal or maximal values.
2. **Complex Structures**: Trees with complex branching structures.
3. **Specific Conditions**: Trees where the root or some vertices have specific properties that might cause the buggy code to fail.

### Step-by-Step Analysis

1. **Minimal Tree**:
   - A tree with only two vertices (root and one child).
   - This can help check if the code handles the simplest case correctly.

2. **Maximal Tree**:
   - A tree with the maximum number of vertices (5000).
   - This can help check if the code handles large inputs efficiently and correctly.

3. **Complex Branching**:
   - A tree with multiple levels of branching.
   - This can help check if the code correctly handles more complex tree structures.

4. **Specific Conditions**:
   - A tree where the root has a high value and all children have low values.
   - A tree where some vertices have very high values and others have very low values.
   - A tree where the sum of child values is just slightly less than the parent value.

### Chosen Test Input

Let's create a test input that combines these aspects:

1. A small tree with a specific condition where the root has a high value and all children have low values.
2. A medium-sized tree with complex branching.
3. A large tree with a specific condition where the sum of child values is just slightly less than the parent value.

### Test Input

```plaintext
3
5
100 1 1 1 1
1 1 3 3
10
10 1 1 1 1 1 1 1 1 1
1 1 2 2 3 3 4 4 5
5000
1000000000 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1


**Task:**
Generate a challenging test input that exposes the bug in the buggy code of the algorithm problem:
Algorithm Problem:
Title: Wonderful Tree!
time_limit_ms: 2000
memory_limit_mb: 256
Description: God's Blessing on This ArrayForces!

A Random Pebble

You are given a tree with $n$ vertices, rooted at vertex $1$. The $i$-th vertex has an integer $a_i$ written on it.

Let $L$ be the set of all direct children$^{\text{∗}}$ of $v$. A tree is called wonderful, if for all vertices $v$ where $L$ is not empty, $$a_v \le \sum_{u \in L}{a_u}.$$ In one operation, you choose any vertex $v$ and increase $a_v$ by $1$.

Find the minimum number of operations needed to make the given tree wonderful!

$^{\text{∗}}$ Vertex $u$ is called a direct child of vertex $v$ if:

  * $u$ and $v$ are connected by an edge, and    * $v$ is on the (unique) path from $u$ to the root of the tree.

Input: Each test contains multiple test cases. The first line of input contains a single integer $t$ ($1 \le t \le 1000$) — the number of test cases. The description of the test cases follows.

The first line of each test case contains a single integer $n$ ($2 \le n \le 5000$) — the number of vertices in the tree.

The second line of each test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le 10^9$) — the values initially written on the vertices.

The third line of each test case contains $n - 1$ integers $p_2, p_3 , \ldots, p_n$ ($1 \le p_i < i$), indicating that there is an edge from vertex $p_i$ to vertex $i$. It is guaranteed that the given edges form a tree.

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

Output: For each test case, output a single integer — the minimum number of operations needed to make the tree wonderful.

Examples:
input:
4
5
9 3 4 1 2
1 1 3 3
2
5 3
1
2
36 54
1
3
0 0 0
1 2
output:
3
2
0
0

Note: The tree in the first test case:

![](CDN_BASE_URL/9a07d26506b9ad6c01c4152da8319590)

You can apply the operation once on vertex $5$ and twice on vertex $2$ to get a wonderful tree.

In the second test case, you can apply the operation twice on vertex $2$ to get a wonderful tree.

In the third and fourth test cases, the tree is already wonderful, so you don't need to apply any operations.

Buggy Code:
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define leng signed(5e3 + 5)
// vector<int> edges[leng];
int a[leng];
// int sum[leng];
int p[leng];
    int n;
void solve(){
    // cin >> n;
    for(int i = 1; i <= n; ++i) {
        cin >> a[i];
    }
    vector<int> edges[n + 1];
    for(int i = 2; i <= n; ++i) {
        cin >> p[i];
        if(p[i] > 0) edges[p[i]].push_back(i);
    }
    vector<vector<int>> dp(n + 1, vector<int>(n + 1, -1));
    function<void(int)> dfs = [&](int cur) -> void{
        // cerr << cur << '\n';
        int sum = 0;
        dp[cur][0] = 0;
        if(edges[cur].empty()) return;
        for(int next: edges[cur]) {
            dfs(next);
            dp[cur][0] += dp[next][0];
            sum += a[next];
        }
        if(sum >= a[cur]) {
            dp[cur][1] = sum - a[cur];
            for(int i = 2; i <= n; ++i) {
                dp[cur][i] = 0;
                for(int next: edges[cur]) {
                    if(dp[next][i - 1] == -1) {
                        dp[cur][i] = -1;
                        break;
                    }
                    dp[cur][i] += dp[next][i - 1];
                }
                if(dp[cur][i] == -1) break;
            }
        } else {
            dp[cur][1] = 0;
            // dp[cur][0] += a[cur] - sum;
            int need = a[cur] - sum;
            int i;
            for(i = 1; i <= n && need > 0; ++i) {
                int tsum = 0;
                for(int next: edges[cur]) {
                    if(dp[next][i] == -1) {
                        tsum = -1;
                        break;
                    }
                    tsum += dp[next][i];
                }
                // if(need )
                if(tsum == -1 || need <= tsum) {
                    dp[cur][0] += i * need;
                    // break;
                    if(i < n) dp[cur][i + 1] = tsum - need;
                    need = 0;
                    for(int j = 1; j <= i; ++j) {
                        dp[cur][j] = 0;
                    }
                } else {
                    dp[cur][0] += i * tsum;
                    need -= tsum;
                }
            }
            // ++i;
            for(; i <= n; ++i)  {
                dp[cur][i] = 0;
                for(int next: edges[cur]) {
                    if(dp[next][i - 1] == -1) {
                        dp[cur][i] = -1;
                        break;
                    }
                    dp[cur][i] += dp[next][i - 1];
                }
                if(dp[cur][i] == -1) break;
            }
        }
        cerr << cur << '\n';
        for(int i = 0; i <= n; ++i) {
            cerr << dp[cur][i] << ' ';
            if(dp[cur][i] == -1) break;
        }
        cerr << '\n';
    };
    dfs(1);
    if(dp[1][0] == -1) cout << 0 << '\n';
    else cout << dp[1][0] << '\n';
}
signed main() {
    // cout << 1LL * (1e9 + 1) * (1e9 + 1) << '\n';
    // int ans = 1e9;
    // ans += 1e9 / 10 * 1e9 / 10;
    // cout << ans << '\n';
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    // solve();
    // cout << cab(4, 2);
    int t;
    cin >> t;
    // solve();
    while(t--) {
            cin >> n;
        if(1000 - t == 79 && n != 4) {
            // int n;
            cout << n << 'b';
            for(int i = 0; i < n; ++i) {
                cin >> a[i];
                cout << a[i] << 'b';
            }
            for(int i = 1; i < n; ++i) {
                cin >> a[i];
                cout << a[i] << 'b';
            }
        }
        solve();
    }
}

**Instructions:**
- Focus on edge cases or scenarios that maximize the failure probability in faulty solutions.
- Due to the output length limit, you should generate a **small-scale** test input that is **complete and valid**.
- Output the test input directly, not code to generate it.

**Output format:**
```plaintext
{test input}
```

Think step by step.

Response:
```plaintext
1
4
1 2 3 4
1 1 1
```


**Task:**
Generate a challenging test input that exposes the bug in the buggy code of the algorithm problem:
Algorithm Problem:
Title: Wonderful Tree!
time_limit_ms: 2000
memory_limit_mb: 256
Description: God's Blessing on This ArrayForces!

A Random Pebble

You are given a tree with $n$ vertices, rooted at vertex $1$. The $i$-th vertex has an integer $a_i$ written on it.

Let $L$ be the set of all direct children$^{\text{∗}}$ of $v$. A tree is called wonderful, if for all vertices $v$ where $L$ is not empty, $$a_v \le \sum_{u \in L}{a_u}.$$ In one operation, you choose any vertex $v$ and increase $a_v$ by $1$.

Find the minimum number of operations needed to make the given tree wonderful!

$^{\text{∗}}$ Vertex $u$ is called a direct child of vertex $v$ if:

  * $u$ and $v$ are connected by an edge, and    * $v$ is on the (unique) path from $u$ to the root of the tree.

Input: Each test contains multiple test cases. The first line of input contains a single integer $t$ ($1 \le t \le 1000$) — the number of test cases. The description of the test cases follows.

The first line of each test case contains a single integer $n$ ($2 \le n \le 5000$) — the number of vertices in the tree.

The second line of each test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le 10^9$) — the values initially written on the vertices.

The third line of each test case contains $n - 1$ integers $p_2, p_3 , \ldots, p_n$ ($1 \le p_i < i$), indicating that there is an edge from vertex $p_i$ to vertex $i$. It is guaranteed that the given edges form a tree.

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

Output: For each test case, output a single integer — the minimum number of operations needed to make the tree wonderful.

Examples:
input:
4
5
9 3 4 1 2
1 1 3 3
2
5 3
1
2
36 54
1
3
0 0 0
1 2
output:
3
2
0
0

Note: The tree in the first test case:

![](CDN_BASE_URL/9a07d26506b9ad6c01c4152da8319590)

You can apply the operation once on vertex $5$ and twice on vertex $2$ to get a wonderful tree.

In the second test case, you can apply the operation twice on vertex $2$ to get a wonderful tree.

In the third and fourth test cases, the tree is already wonderful, so you don't need to apply any operations.

Buggy Code:
#include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define all(s) s.begin(), s.end()
#ifndef LOCALDEBUG
#define LOCALDEBUG false
#endif
typedef long long ll;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef pair<int, int> pii;

const int MAXN = 5000;
ll value[MAXN + 12];
ll child_sum[MAXN + 12];
int p[MAXN + 12];
vvi children;

ll slack[MAXN + 12];
const ll INF = 1e17;

void get_slack(int src = 1)
{
    child_sum[src] = 0;

    if (children[src].empty())
    {
        slack[src] = INF;
        return;
    }

    for (int a : children[src])
    {
        get_slack(a);
        child_sum[src] += value[a];
    }

    slack[src] = child_sum[src] - value[src];
}

struct Node
{
    ll id, depth, slk;
    friend bool operator<(const Node &l, const Node &r)
    {
        return l.depth < r.depth;
    }
};

// nodes on path to closest_slack have slack 0, they must be updated, # = depth
Node closest_slack(int src)
{
    Node ans = {src, 0, slack[src]};
    if (slack[src] <= 0)
        ans.depth = INF;

    for (int a : children[src])
    {
        Node opt = closest_slack(a);
        opt.depth++;

        ans = min(ans, opt);
    }

    return ans;
}

ll make_wonderful(int src = 1)
{
    ll ans = 0;

    for (int a : children[src])
        ans += make_wonderful(a);

    // all children have >= 0 slack

    get_slack(src);

    if (slack[src] >= 0)
        return ans;

    ll need = -slack[src];

    while (need)
    {
        Node close = closest_slack(src);
        ll delta = min(need, close.slk);

        need -= delta;
        slack[close.id] -= delta;

        ans += close.depth * delta;
    }

    return ans;
}

void solve()
{
    int n;
    cin >> n;

    children.clear();
    children.resize(n + 1);

    for (int i = 1; i <= n; i++)
        cin >> value[i];
    for (int i = 2; i <= n; i++)
    {
        cin >> p[i];
        children[p[i]].push_back(i);
    }

    get_slack();

    cout << make_wonderful() << '\n';
}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    int t = 1;
    cin >> t;
    while (t--)
    {
        solve();
    }
}

**Instructions:**
- Focus on edge cases or scenarios that maximize the failure probability in faulty solutions.
- Due to the output length limit, you should generate a **small-scale** test input that is **complete and valid**.
- Output the test input directly, not code to generate it.

**Output format:**
```plaintext
{test input}
```

Think step by step.

Response:
To generate a challenging test input that exposes the bug in the given code, we need to consider scenarios where the tree structure and values might cause the algorithm to fail. Here are the steps to think through this:

1. **Edge Cases:**
   - Trees with only a few nodes.
   - Trees where the root has no children.
   - Trees where all nodes have the same value.
   - Trees where the root has a very high value compared to its children.
   - Trees where the root has a very low value compared to its children.

2. **Complex Structures:**
   - Trees with multiple levels of children.
   - Trees with a deep hierarchy.
   - Trees where the values are distributed in a way that requires multiple operations to make the tree wonderful.

3. **Specific Bug Triggers:**
   - The code might fail when the slack values are not correctly calculated for nodes with multiple children.
   - The code might fail when the closest slack node is not correctly identified.

Given these considerations, let's create a small-scale test input that is likely to expose the bug:

```plaintext
1
5
1 2 3 4 5
1 1 2 2
```

**Explanation:**
- **Tree Structure:**
  - Root (1) has two children: 2 and 3.
  - Node 2 has two children: 4 and 5.
- **Values:**
  - Root (1) has value 1.
  - Node 2 has value 2.
  - Node 3 has value 3.
  - Node 4 has value 4.
  - Node 5 has value 5.

**Expected Output:**
- The tree is not wonderful initially because the root (1) has a value of 1, but its children (2 and 3) have values that sum to 5.
- Node 2 is not wonderful because its value is 2, but its children (4 and 5) have values that sum to 9.
- The minimum number of operations needed to make the tree wonderful is 4:
  - Increase the value of node 1 by 4 to make it 5 (1 + 4 = 5).
  - The tree becomes wonderful because:
    - Root (1) has value 5, and its children (2 and 3) have values that sum to 5.
    - Node 2 has value 2, and its children (4 and 5) have values that sum to 9.

This test input should challenge the algorithm to correctly calculate the slack values and identify the nodes that need to be updated to make the tree wonderful.


**Task:**
Generate a challenging test input that exposes the bug in the buggy code of the algorithm problem:
Algorithm Problem:
Title: Wonderful Tree!
time_limit_ms: 2000
memory_limit_mb: 256
Description: God's Blessing on This ArrayForces!

A Random Pebble

You are given a tree with $n$ vertices, rooted at vertex $1$. The $i$-th vertex has an integer $a_i$ written on it.

Let $L$ be the set of all direct children$^{\text{∗}}$ of $v$. A tree is called wonderful, if for all vertices $v$ where $L$ is not empty, $$a_v \le \sum_{u \in L}{a_u}.$$ In one operation, you choose any vertex $v$ and increase $a_v$ by $1$.

Find the minimum number of operations needed to make the given tree wonderful!

$^{\text{∗}}$ Vertex $u$ is called a direct child of vertex $v$ if:

  * $u$ and $v$ are connected by an edge, and    * $v$ is on the (unique) path from $u$ to the root of the tree.

Input: Each test contains multiple test cases. The first line of input contains a single integer $t$ ($1 \le t \le 1000$) — the number of test cases. The description of the test cases follows.

The first line of each test case contains a single integer $n$ ($2 \le n \le 5000$) — the number of vertices in the tree.

The second line of each test case contains $n$ integers $a_1, a_2, \ldots, a_n$ ($0 \le a_i \le 10^9$) — the values initially written on the vertices.

The third line of each test case contains $n - 1$ integers $p_2, p_3 , \ldots, p_n$ ($1 \le p_i < i$), indicating that there is an edge from vertex $p_i$ to vertex $i$. It is guaranteed that the given edges form a tree.

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

Output: For each test case, output a single integer — the minimum number of operations needed to make the tree wonderful.

Examples:
input:
4
5
9 3 4 1 2
1 1 3 3
2
5 3
1
2
36 54
1
3
0 0 0
1 2
output:
3
2
0
0

Note: The tree in the first test case:

![](CDN_BASE_URL/9a07d26506b9ad6c01c4152da8319590)

You can apply the operation once on vertex $5$ and twice on vertex $2$ to get a wonderful tree.

In the second test case, you can apply the operation twice on vertex $2$ to get a wonderful tree.

In the third and fourth test cases, the tree is already wonderful, so you don't need to apply any operations.

Buggy Code:
import sys, math, queue
import heapq as hq
input = sys.stdin.readline
out = []

MOD = 10 ** 9 + 7

ivar = lambda: int(input())
ivars = lambda: map(int, input().split())
ilist = lambda: list(map(int, input().split()))
stri = lambda: input().strip()

class Tree:

    # Number of nodes and adjacency list
    def __init__(self, n, Adj=None):
        self.n = n
        if Adj is None:
            self.Adj = [[] for _ in range(n+1)]
        else:
            self.Adj = Adj

    # Distances to all nodes (req. bfs_parents) -- O(V)
    def bfs_dists(self, root=1):
        D = [-1 for _ in range(self.n+1)]

        for node, prev in self.bfs_parents(root):
            if node == root:
                D[node] = 0
            else:
                D[node] = D[prev] + 1

        return D

    # Generator, yields all nodes with their parents -- O(V+E)
    def bfs_parents(self, root=1, prev=-1):
        Q = queue.Queue()
        Q.put_nowait((root, prev))

        yield root, -1

        while not Q.empty():
            prev, ancestor = Q.get_nowait()
            for node in self.Adj[prev]:
                if node != ancestor:
                    yield node, prev

                    Q.put_nowait((node, prev))

    # Generator, all nodes with their parents -- O(V+E)
    def dfs_parents(self, root=1, parent=-1):
        stack = [(root, parent)]
        while stack != []:
            cur, prev = stack.pop()

            yield cur, prev

            for node in self.Adj[cur]:
                if node != prev:
                    stack.append((node, cur))

    # Generator, all nodes including backtracked nodes -- O(V+E)
    def dfs_backtrack(self, root=1):
        stack = [(root, 0)]
        while stack != []:
            cur, prev = stack.pop()

            yield cur, prev

            if prev >= 0:
                first = True
                for node in self.Adj[cur]:
                    if node != prev:
                        if first:
                            stack.append((cur, -2))
                            first = False
                        else:
                            stack.append((cur, -1))
                        stack.append((node, cur))

def solve():
    n = ivar()
    A = ilist()
    P = ilist()
    Adj = [[] for _ in range(n+1)]
    for i, x in enumerate(P):
        Adj[i+2].append(x)
        Adj[x].append(i+2)

    T = Tree(n, Adj)

    parents = [-1 for _ in range(n+1)]

    diffs = [-math.inf for _ in range(n+1)]

    for cur, par in T.dfs_parents():
        parents[cur] = par
        if cur == 1 or len(T.Adj[cur]) > 1:
            s = 0
            for child in T.Adj[cur]:
                if child != par:
                    s += A[child-1]

            diffs[cur] = A[cur-1] - s

    min_heights = [math.inf for _ in range(n+1)]
    for cur, prev in T.dfs_backtrack():
        if cur != 1 and len(Adj[cur]) == 1:
            min_heights[cur] = 0
        elif prev == -2:
            for child in T.Adj[cur]:
                if child != parents[cur]:
                    min_heights[cur] = min(min_heights[cur], min_heights[child] + 1)

    D = T.bfs_dists(1)

    ans = 0
    for node, parent in T.dfs_parents():
        if diffs[node] > 0:
            for child, par in T.bfs_parents(node, parent):
                if diffs[child] < 0:
                    ans += min(diffs[node], -diffs[child]) * (D[child] - D[node])
                    diffs[node] += diffs[child]
                    if diffs[node] <= 0:
                        break

    return ans

for _ in range(int(input())):
    out.append(solve())

print("\n".join(map(str, out)))

**Instructions:**
- Focus on edge cases or scenarios that maximize the failure probability in faulty solutions.
- Due to the output length limit, you should generate a **small-scale** test input that is **complete and valid**.
- Output the test input directly, not code to generate it.

**Output format:**
```plaintext
{test input}
```

Think step by step.

Response:
To expose the bug in the given buggy code, we need to focus on edge cases or scenarios that maximize the failure probability. Let's break down the problem and identify potential issues:

1. **Tree Structure and Values**: The tree structure and the values on the vertices can significantly affect the algorithm. We need to consider:
   - Trees with long paths.
   - Trees with many branches.
   - Trees where the root or some vertices have large values.
   - Trees where the sum condition is barely met or not met at all.

2. **Buggy Code Analysis**:
   - The code uses a depth-first search (DFS) and breadth-first search (BFS) to calculate the differences and minimum heights.
   - It calculates the difference `diffs` between the value of a vertex and the sum of its children.
   - It then tries to correct the differences by iterating through the tree.

3. **Potential Issues**:
   - The code might not correctly handle cases where the tree has a complex structure with many branches.
   - The code might not correctly handle cases where the values on the vertices are very large or very small.
   - The code might not correctly handle cases where the tree is almost balanced but not quite.

Given these considerations, let's create a test case that could expose the bug:

### Test Case
We will create a tree with 5 vertices, where the root has a large value, and the children have small values. This should force the code to perform many operations to make the tree wonderful.

```plaintext
1
5
100 1 1 1 1
1 1 1 1
```

### Explanation
- **Number of Test Cases**: 1
- **Number of Vertices**: 5
- **Values on Vertices**: 100, 1, 1, 1, 1
- **Edges**: 1 1 1 1 (indicating that vertices 2, 3, 4, and 5 are all children of vertex 1)

This test case will force the code to perform many operations to make the tree wonderful, as the root vertex (1) has a value of 100, and all its children have a value of 1. The sum of the children's values is 4, which is much less than 100. Therefore, the code will need to increase the values of the children significantly to make the tree wonderful.

### Expected Output
The expected output for this test case is 96, as the code needs to increase the values of the children by 96 to make the tree wonderful.

```plaintext
1
5
100 1 1 1 1
1 1 1 1
```