**Task:**
Generate a challenging test input that exposes the bug in the buggy code of the algorithm problem:
Algorithm Problem:
Title: Rectangle Arrangement
time_limit_ms: 1000
memory_limit_mb: 256
Description: You are coloring an infinite square grid, in which all cells are initially white. To do this, you are given $n$ stamps. Each stamp is a rectangle of width $w_i$ and height $h_i$.

You will use each stamp exactly once to color a rectangle of the same size as the stamp on the grid in black. You cannot rotate the stamp, and for each cell, the stamp must either cover it fully or not cover it at all. You can use the stamp at any position on the grid, even if some or all of the cells covered by the stamping area are already black.

What is the minimum sum of the perimeters of the connected regions of black squares you can obtain after all the stamps have been used?

Input: Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 500$). The description of the test cases follows.

The first line of each test case contains a single integer $n$ ($1 \le n \le 100$).

The $i$-th of the next $n$ lines contains two integers $w_i$ and $h_i$ ($1 \le w_i, h_i \le 100$).

Output: For each test case, output a single integer — the minimum sum of the perimeters of the connected regions of black squares you can obtain after all the stamps have been used.

Examples:
input:
5
5
1 5
2 4
3 3
4 2
5 1
3
2 2
1 1
1 2
1
3 2
3
100 100
100 100
100 100
4
1 4
2 3
1 5
3 2
output:
20
8
10
400
16

Note: In the first test case, the stamps can be used as shown on the left. Each stamp is highlighted in its own color for clarity.

![](CDN_BASE_URL/877686333ced56f689851506a90eefb8)

After all these stamps are used, there is one black region (as shown on the right), and its perimeter is $20$. It can be shown that there is no way of using the stamps that yields a lower total perimeter.

In the second test case, the second and third stamps can be used entirely inside the first one, so the minimum perimeter is equal to $8$.

Buggy Code:
t = int(input())
for i in range(t):
    n = int(input())
    l =[]
    d={}
    for k in range(n):
        l.append(list(map(int,input().split())))
    for [a,b] in l:
        if a in d:
            if d[a] < b:
                d[a] = b
        else:
            d[a] = b
    k = [key for key in d]
    k.sort()
    print(2*k[-1]+ 2*d[k[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
3
1
1 1
2
1 1
1 2
3
1 1
1 2
1 3
```


**Task:**
Generate a challenging test input that exposes the bug in the buggy code of the algorithm problem:
Algorithm Problem:
Title: Rectangle Arrangement
time_limit_ms: 1000
memory_limit_mb: 256
Description: You are coloring an infinite square grid, in which all cells are initially white. To do this, you are given $n$ stamps. Each stamp is a rectangle of width $w_i$ and height $h_i$.

You will use each stamp exactly once to color a rectangle of the same size as the stamp on the grid in black. You cannot rotate the stamp, and for each cell, the stamp must either cover it fully or not cover it at all. You can use the stamp at any position on the grid, even if some or all of the cells covered by the stamping area are already black.

What is the minimum sum of the perimeters of the connected regions of black squares you can obtain after all the stamps have been used?

Input: Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 500$). The description of the test cases follows.

The first line of each test case contains a single integer $n$ ($1 \le n \le 100$).

The $i$-th of the next $n$ lines contains two integers $w_i$ and $h_i$ ($1 \le w_i, h_i \le 100$).

Output: For each test case, output a single integer — the minimum sum of the perimeters of the connected regions of black squares you can obtain after all the stamps have been used.

Examples:
input:
5
5
1 5
2 4
3 3
4 2
5 1
3
2 2
1 1
1 2
1
3 2
3
100 100
100 100
100 100
4
1 4
2 3
1 5
3 2
output:
20
8
10
400
16

Note: In the first test case, the stamps can be used as shown on the left. Each stamp is highlighted in its own color for clarity.

![](CDN_BASE_URL/877686333ced56f689851506a90eefb8)

After all these stamps are used, there is one black region (as shown on the right), and its perimeter is $20$. It can be shown that there is no way of using the stamps that yields a lower total perimeter.

In the second test case, the second and third stamps can be used entirely inside the first one, so the minimum perimeter is equal to $8$.

Buggy Code:
t = int(input())
for _ in range(t):
    n = int(input())
    ordh = []
    toul = []
    for _ in range(n):
        n1, n2 = map(int, input().split())
        ordh.append(n1)
        toul.append(n2)
    s=0
    s+=max(toul)+max(ordh)
    tableaux_lies = sorted(zip(toul, ordh))
    toul, ordh = zip(*tableaux_lies)
    toul=toul[::-1]
    ordh=ordh[::-1]
    ttt=max(toul)
    aaa=ordh[0]
    s+=aaa+min(toul)
    if ((ordh[0]+toul[0])*2!=(max(toul)+max(ordh))*2):
        for i in range (len(toul)):
            if (ordh[i]>=aaa):
                s+=ordh[i]-aaa+ttt-toul[i]
                aaa=ordh[i]
                ttt=toul[i]
        if (aaa==ordh[0]) :
            s-=min(toul)
            s+=max(toul)
        print(s)
    else :
        print((ordh[0]+toul[0])*2)

**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
5
5
1 5
2 4
3 3
4 2
5 1
3
2 2
1 1
1 2
1
3 2
3
100 100
100 100
100 100
4
1 4
2 3
1 5
3 2
```


**Task:**
Generate a challenging test input that exposes the bug in the buggy code of the algorithm problem:
Algorithm Problem:
Title: Rectangle Arrangement
time_limit_ms: 1000
memory_limit_mb: 256
Description: You are coloring an infinite square grid, in which all cells are initially white. To do this, you are given $n$ stamps. Each stamp is a rectangle of width $w_i$ and height $h_i$.

You will use each stamp exactly once to color a rectangle of the same size as the stamp on the grid in black. You cannot rotate the stamp, and for each cell, the stamp must either cover it fully or not cover it at all. You can use the stamp at any position on the grid, even if some or all of the cells covered by the stamping area are already black.

What is the minimum sum of the perimeters of the connected regions of black squares you can obtain after all the stamps have been used?

Input: Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 500$). The description of the test cases follows.

The first line of each test case contains a single integer $n$ ($1 \le n \le 100$).

The $i$-th of the next $n$ lines contains two integers $w_i$ and $h_i$ ($1 \le w_i, h_i \le 100$).

Output: For each test case, output a single integer — the minimum sum of the perimeters of the connected regions of black squares you can obtain after all the stamps have been used.

Examples:
input:
5
5
1 5
2 4
3 3
4 2
5 1
3
2 2
1 1
1 2
1
3 2
3
100 100
100 100
100 100
4
1 4
2 3
1 5
3 2
output:
20
8
10
400
16

Note: In the first test case, the stamps can be used as shown on the left. Each stamp is highlighted in its own color for clarity.

![](CDN_BASE_URL/877686333ced56f689851506a90eefb8)

After all these stamps are used, there is one black region (as shown on the right), and its perimeter is $20$. It can be shown that there is no way of using the stamps that yields a lower total perimeter.

In the second test case, the second and third stamps can be used entirely inside the first one, so the minimum perimeter is equal to $8$.

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

@SuppressWarnings("unused")

public class Codeforces {

    public static void solve(Scanner scanner) {

        int size = scanner.nextInt();
        int[] width = new int[size];
        int[] height = new int[size];

        for (int i = 0; i < size; i++)
        {
            width[i] = scanner.nextInt();
            height[i] = scanner.nextInt();
        }

        Arrays.sort(width);
        Arrays.sort(height);

        int result = 0;

        if (size == 1)
        {
            result = 2 * (width[0] + height[0]);
            System.out.println(result);
        }
        else
        {
            if (height[0] < height[size - 1])
            {
                result = width[size - 1] + height[size - 1] + ((height[size - 1] - height[0] + 1) * 2);
            }
            else
            {
                result = width[size - 1] + height[size - 1] + (height[size - 1] * 2);
            }

            System.out.println(result);
        }

    }

    public static void main(String args[]) {

        Scanner scanner = new Scanner(System.in);

        int test = scanner.nextInt();
        scanner.nextLine();

        for (int t = 0; t < test; t++)
        {
            solve(scanner);
        }

        scanner.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 provided buggy code, we need to focus on edge cases and scenarios that highlight the incorrect assumptions in the code. The buggy code sorts the widths and heights independently and then uses these sorted values to calculate the perimeter. This approach is flawed because it does not consider the optimal placement of stamps to minimize the total perimeter of the black regions.

### Steps to Generate the Test Input:
1. **Single Stamp Case**: Test with a single stamp to ensure the basic calculation is correct.
2. **Equal Width and Height Stamps**: Test with stamps that have the same width and height to see if the code handles equal values correctly.
3. **Different Width and Height Stamps**: Test with stamps that have different widths and heights to see if the code correctly handles the perimeter calculation.
4. **Stamps with One Dimension Much Larger**: Test with stamps where one dimension is significantly larger than the other to see if the code handles extreme values correctly.
5. **Multiple Stamps with Varying Dimensions**: Test with multiple stamps to see if the code can handle a combination of different dimensions.

### Challenging Test Input:
```plaintext
5
1
3 2
3
2 2
1 1
1 2
4
1 4
2 3
1 5
3 2
5
1 5
2 4
3 3
4 2
5 1
3
100 1
100 1
100 1
```

### Explanation:
1. **Single Stamp Case**:
   - Test case: `1 3 2`
   - Expected output: `10` (Perimeter of a 3x2 rectangle is 2 * (3 + 2) = 10)

2. **Equal Width and Height Stamps**:
   - Test case: `3 2 2 1 1 1 2`
   - Expected output: `8` (The smallest rectangle can cover the others, so the perimeter is 2 * (2 + 2) = 8)

3. **Different Width and Height Stamps**:
   - Test case: `4 1 4 2 3 1 5 3 2`
   - Expected output: `16` (The optimal arrangement might be to place the largest rectangle and then fit the others inside it or adjacent to it)

4. **Stamps with One Dimension Much Larger**:
   - Test case: `5 1 5 2 4 3 3 4 2 5 1`
   - Expected output: `20` (The optimal arrangement might be to place the largest rectangle and then fit the others inside it or adjacent to it)

5. **Multiple Stamps with Varying Dimensions**:
   - Test case: `3 100 1 100 1 100 1`
   - Expected output: `400` (Each 100x1 rectangle will have a perimeter of 202, and since they are not connected, the total perimeter is 3 * 202 = 400)

This test input covers a range of scenarios that should help expose the bugs in the provided code.


**Task:**
Generate a challenging test input that exposes the bug in the buggy code of the algorithm problem:
Algorithm Problem:
Title: Rectangle Arrangement
time_limit_ms: 1000
memory_limit_mb: 256
Description: You are coloring an infinite square grid, in which all cells are initially white. To do this, you are given $n$ stamps. Each stamp is a rectangle of width $w_i$ and height $h_i$.

You will use each stamp exactly once to color a rectangle of the same size as the stamp on the grid in black. You cannot rotate the stamp, and for each cell, the stamp must either cover it fully or not cover it at all. You can use the stamp at any position on the grid, even if some or all of the cells covered by the stamping area are already black.

What is the minimum sum of the perimeters of the connected regions of black squares you can obtain after all the stamps have been used?

Input: Each test contains multiple test cases. The first line contains the number of test cases $t$ ($1 \le t \le 500$). The description of the test cases follows.

The first line of each test case contains a single integer $n$ ($1 \le n \le 100$).

The $i$-th of the next $n$ lines contains two integers $w_i$ and $h_i$ ($1 \le w_i, h_i \le 100$).

Output: For each test case, output a single integer — the minimum sum of the perimeters of the connected regions of black squares you can obtain after all the stamps have been used.

Examples:
input:
5
5
1 5
2 4
3 3
4 2
5 1
3
2 2
1 1
1 2
1
3 2
3
100 100
100 100
100 100
4
1 4
2 3
1 5
3 2
output:
20
8
10
400
16

Note: In the first test case, the stamps can be used as shown on the left. Each stamp is highlighted in its own color for clarity.

![](CDN_BASE_URL/877686333ced56f689851506a90eefb8)

After all these stamps are used, there is one black region (as shown on the right), and its perimeter is $20$. It can be shown that there is no way of using the stamps that yields a lower total perimeter.

In the second test case, the second and third stamps can be used entirely inside the first one, so the minimum perimeter is equal to $8$.

Buggy Code:
// package CF;

import java.io.InputStream;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        InputStream is = args.length > 0 && "LOCAL".equals(args[0]) ? Solution.class.getResourceAsStream("/input.txt") : System.in;
        Scanner sc = new Scanner(is);
        long t = sc.nextLong();
        while (t-- > 0) {
            int n = sc.nextInt();
            Integer[][] arr = new Integer[n][2];
            for (int i=0; i<n; i++) {
                arr[i][0] = sc.nextInt();
                arr[i][1] = sc.nextInt();
            }
            Arrays.sort(arr, (a,b) -> Integer.compare(b[1], a[1]));
            long ans = 2L * (arr[0][0] + arr[0][1]);
            for(int i=1; i<n; i++) {
                ans +=  Math.abs(2L * (arr[i][0] + arr[i][1]) - (2L * ((Math.min(arr[i][0], arr[i-1][0])) + (Math.min(arr[i][1], arr[i-1][1])))));
            }
            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 given buggy code, we need to focus on edge cases and scenarios that maximize the failure probability. The bug in the code seems to be related to the incorrect calculation of the perimeter when multiple rectangles overlap or are placed in specific configurations.

### Step-by-Step Analysis:
1. **Understanding the Bug**: The code sorts the rectangles by height in descending order and then calculates the perimeter of the combined region. However, it does not correctly account for the overlapping areas or the optimal placement of rectangles.

2. **Edge Cases**:
   - **Overlapping Rectangles**: Test cases where rectangles overlap significantly.
   - **Non-overlapping Rectangles**: Test cases where rectangles are placed far apart.
   - **Mixed Sizes**: Test cases with a mix of large and small rectangles.
   - **Single Rectangle**: Test cases with only one rectangle.

3. **Challenging Configuration**:
   - A configuration where placing rectangles in a specific order can significantly reduce the perimeter.
   - A configuration where the sorting by height does not yield the optimal solution.

### Chosen Test Case:
Let's consider a test case where we have two large rectangles and two smaller rectangles. The smaller rectangles are placed inside the larger ones, which should result in a smaller total perimeter.

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

### Explanation:
- **First Rectangle (5x5)**: This is the largest rectangle.
- **Second Rectangle (4x4)**: This can be placed inside the first rectangle.
- **Third Rectangle (2x2)**: This can be placed inside the second rectangle.
- **Fourth Rectangle (1x1)**: This can be placed inside the third rectangle.

By placing the smaller rectangles inside the larger ones, the total perimeter of the combined region should be minimized. However, the buggy code might not correctly account for this nested placement and might calculate a higher perimeter.

### Output:
```plaintext
1
4
5 5
4 4
2 2
1 1
```


**Task:**
Generate a challenging test input that exposes the bug in the buggy code of the algorithm problem:
Algorithm Problem:
Title: Maximize the Root
time_limit_ms: 3000
memory_limit_mb: 256
Description: You are given a rooted tree, consisting of $n$ vertices. The vertices in the tree are numbered from $1$ to $n$, and the root is the vertex $1$. The value $a_i$ is written at the $i$-th vertex.

You can perform the following operation any number of times (possibly zero): choose a vertex $v$ which has at least one child; increase $a_v$ by $1$; and decrease $a_u$ by $1$ for all vertices $u$ that are in the subtree of $v$ (except $v$ itself). However, after each operation, the values on all vertices should be non-negative.

Your task is to calculate the maximum possible value written at the root using the aforementioned operation.

Input: The first line contains a single integer $t$ ($1 \le t \le 10^4$) — the number of test cases.

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

The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($0 \le a_i \le 10^9$) — the initial values written at vertices.

The third line contains $n-1$ integers $p_2, p_3, \dots, p_n$ ($1 \le p_i \le n$), where $p_i$ is the parent of the $i$-th vertex in the tree. Vertex $1$ is the root.

Additional constraint on the input: the sum of $n$ over all test cases doesn't exceed $2 \cdot 10^5$.

Output: For each test case, print a single integer — the maximum possible value written at the root using the aforementioned operation.

Examples:
input:
3
4
0 1 0 2
1 1 3
2
3 0
1
5
2 5 3 9 6
3 1 5 2
output:
1
3
6

Note: In the first test case, the following sequence of operations is possible:

  * perform the operation on $v=3$, then the values on the vertices will be $[0, 1, 1, 1]$;    * perform the operation on $v=1$, then the values on the vertices will be $[1, 0, 0, 0]$.

Buggy Code:
#include<bits/stdc++.h>
using namespace std ;
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
#define int long long
const int N = 2e5+5 ;
const int INF = 1e18  ;
const int mod = 1e9 + 7 ;
const double pi = acos(-1.0) ;
template <typename T>
using order_set = tree<T, null_type,less<T>, rb_tree_tag,tree_order_statistics_node_update>;
int fact[N] ;
int n ;
int a[N] ;
int lev[N] ;
int par[N] ;
vector < int > graph[N] , level[N] ;

int big_mod(int key, int pow)
{
    int ans = 1 ;
    if(pow == 0) return 1 ;
    ans = big_mod(key,pow/2) ;
    ans = 1LL * ans * ans % mod ;
    if(pow&1) ans = 1LL * ans * key % mod;
    return ans ;
}

int ncr(int n , int r){
    int nn = fact[n] ;
    int rr = ((fact[r]%mod)*(fact[n-r]%mod))%mod ;
    nn = nn * 1ll * big_mod(rr , mod-2) ;
    nn %= mod ;
    return nn ;

}

void solve(){
    cin >> n ;
    for(int i = 0 ; i <= n ; i++){
        graph[i].clear() ;
        level[i].clear() ;
        lev[i] = -1 ;

    }
    for(int i = 1 ; i <= n ; i++){
        cin >> a[i] ;
    }
    for(int i = 2 ; i <= n ; i++){
        int x ;
        cin >> x ;
        par[i] = x ;
        graph[x].push_back(i) ;
    }
    for(int i = 0 ; i <= n ; i++){
        lev[i] = -1 ;
    }
    lev[1] = 0 ;
    level[0].push_back(1) ;
    queue < int > q ;
    q.push(1) ;
    int mx = 0 ;
    while(!q.empty()){
            int fnt = q.front() ;
            q.pop() ;
            for(auto it : graph[fnt]){
                if(lev[it] == -1){
                    lev[it] = lev[fnt] + 1 ;
                    level[lev[it]].push_back(it) ;
                    mx = max(lev[it] , mx) ;
                    q.push(it) ;
                }
            }
    }

    //cout << mx << endl ;
    if(mx == 1){
            int ans = 1e6 ;
    for(auto it : level[1]){
        ans = min(a[it] , ans) ;
    }
    cout << ans + a[1] << endl  ;
    return ;

    }

    for(int i = 0 ; i <= n ; i++){
        lev[i] = 1e9  ;
    }

    while(mx > 1){
        for(auto it : level[mx]){
            int p = par[it] ;
            if(a[p] >= a[it] ){
                lev[p] = min(lev[p] , a[it]) ;
            }
            else{
                int val = a[p] + a[it] ;
                val /= 2 ;
                lev[p] = min(lev[p] , val) ;
            }
        }
        mx-- ;
    }

    int ans = 1e6 ;
    for(auto it : level[1]){
        ans = min(lev[it] , ans) ;
    }
    cout << ans + a[1] << endl  ;

    for(int i = 0 ; i <= n ; i++){
        graph[i].clear() ;
        level[i].clear() ;
        lev[i] = -1 ;

    }

}

int32_t main()
{

    ios_base :: sync_with_stdio(false) ; cin.tie(NULL) ; cout.tie(NULL) ;

    fact[0] = 1 , fact[1] = 1 ;
    for(int i = 2 ; i < N ; i++){
        fact[i] =((fact[i-1]%mod)*1ll*(i%mod)) % mod ;
    }

    int t= 1 ;
    cin >> t ;
    int T = 1 ;
    while(t--){
        //cout << " CAs e "<< 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 test input that exposes the bug in the given buggy code, we need to consider scenarios that are likely to cause the code to fail. Here are some potential edge cases and scenarios:

1. **Tree with a single level of children**: This can help test the logic when the tree is very shallow.
2. **Tree with a deep hierarchy**: This can help test the logic when the tree is deep.
3. **Tree with a single path from root to leaf**: This can help test the logic when the tree is essentially a linked list.
4. **Tree with large values at the leaves**: This can help test the logic when the values at the leaves are much larger than the values at the root.
5. **Tree with small values at the leaves**: This can help test the logic when the values at the leaves are much smaller than the values at the root.

Given these considerations, let's create a small-scale test input that includes a deep hierarchy and large values at the leaves. This will help expose potential issues in the code's handling of deep trees and large values.

Here is the test input:

```plaintext
1
5
0 100 100 100 100
1 1 2 2
```

Explanation:
- **Test Case Count**: 1
- **Number of Vertices**: 5
- **Values at Vertices**: [0, 100, 100, 100, 100]
- **Parent Array**: [1, 1, 2, 2]

This test case creates a tree with the following structure:
- Vertex 1 (root) has two children: Vertex 2 and Vertex 3.
- Vertex 2 has two children: Vertex 4 and Vertex 5.

All the leaf nodes have large values (100), and the root node has a value of 0. This should challenge the code to correctly distribute the values to maximize the value at the root.


**Task:**
Generate a challenging test input that exposes the bug in the buggy code of the algorithm problem:
Algorithm Problem:
Title: Maximize the Root
time_limit_ms: 3000
memory_limit_mb: 256
Description: You are given a rooted tree, consisting of $n$ vertices. The vertices in the tree are numbered from $1$ to $n$, and the root is the vertex $1$. The value $a_i$ is written at the $i$-th vertex.

You can perform the following operation any number of times (possibly zero): choose a vertex $v$ which has at least one child; increase $a_v$ by $1$; and decrease $a_u$ by $1$ for all vertices $u$ that are in the subtree of $v$ (except $v$ itself). However, after each operation, the values on all vertices should be non-negative.

Your task is to calculate the maximum possible value written at the root using the aforementioned operation.

Input: The first line contains a single integer $t$ ($1 \le t \le 10^4$) — the number of test cases.

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

The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($0 \le a_i \le 10^9$) — the initial values written at vertices.

The third line contains $n-1$ integers $p_2, p_3, \dots, p_n$ ($1 \le p_i \le n$), where $p_i$ is the parent of the $i$-th vertex in the tree. Vertex $1$ is the root.

Additional constraint on the input: the sum of $n$ over all test cases doesn't exceed $2 \cdot 10^5$.

Output: For each test case, print a single integer — the maximum possible value written at the root using the aforementioned operation.

Examples:
input:
3
4
0 1 0 2
1 1 3
2
3 0
1
5
2 5 3 9 6
3 1 5 2
output:
1
3
6

Note: In the first test case, the following sequence of operations is possible:

  * perform the operation on $v=3$, then the values on the vertices will be $[0, 1, 1, 1]$;    * perform the operation on $v=1$, then the values on the vertices will be $[1, 0, 0, 0]$.

Buggy Code:
#include <iostream>
#include <vector>
#include <algorithm>
#include <climits>
#include <unordered_map>
#include <cmath>
#include <string>
#include <stack>
#include <set>
#include <map>
#include <queue>
#include <cstring>
#include <cmath>
#define int long long int
using namespace std;
#define MODULO 998244353

int dfs(vector<vector<int>> &tree, vector<int> &a, int node){
    if(tree[node].size()==0){
        return a[node];
    }

    int mn = 1000000001;
    for (int i = 0; i < tree[node].size(); i++)
    {
        mn = min(mn, dfs(tree, a, tree[node][i]));
    }

    if(node==0){
        return a[node]+mn;
    }
    if(mn<a[node]){
        return a[node];
    }
    return floor((a[node]+mn)/2.0);
}

void solve()
{
    int n;
    cin>>n;
    vector<int> a(n);
    for (int i = 0; i < n; i++)
    {
        cin>>a[i];
    }

    vector<vector<int>> tree(n, vector<int>());
    int u;
    for (int i = 1; i < n; i++)
    {
        cin>>u;
        u--;
        tree[u].push_back(i);
    }
    // cout<<"hello"<<endl;
    // for (int i = 0; i < n; i++)
    // {
    //     for (int j = 0; j < tree[i].size(); j++)
    //     {
    //         cout<<tree[i][j]<<" ";
    //     }
    //     cout<<endl;
    // }

    cout<<dfs(tree, a, 0)<<endl;

}

int32_t main()
{

    int t;
    t = 1;
    cin >> t;

    for (int _ = 0; _ < t; _++)
    {
        solve();
    }
    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
3
4
0 1 2 3
1 1 2
2
0 0
1
5
0 0 1 1 2
1 1 3 3
```


**Task:**
Generate a challenging test input that exposes the bug in the buggy code of the algorithm problem:
Algorithm Problem:
Title: Maximize the Root
time_limit_ms: 3000
memory_limit_mb: 256
Description: You are given a rooted tree, consisting of $n$ vertices. The vertices in the tree are numbered from $1$ to $n$, and the root is the vertex $1$. The value $a_i$ is written at the $i$-th vertex.

You can perform the following operation any number of times (possibly zero): choose a vertex $v$ which has at least one child; increase $a_v$ by $1$; and decrease $a_u$ by $1$ for all vertices $u$ that are in the subtree of $v$ (except $v$ itself). However, after each operation, the values on all vertices should be non-negative.

Your task is to calculate the maximum possible value written at the root using the aforementioned operation.

Input: The first line contains a single integer $t$ ($1 \le t \le 10^4$) — the number of test cases.

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

The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($0 \le a_i \le 10^9$) — the initial values written at vertices.

The third line contains $n-1$ integers $p_2, p_3, \dots, p_n$ ($1 \le p_i \le n$), where $p_i$ is the parent of the $i$-th vertex in the tree. Vertex $1$ is the root.

Additional constraint on the input: the sum of $n$ over all test cases doesn't exceed $2 \cdot 10^5$.

Output: For each test case, print a single integer — the maximum possible value written at the root using the aforementioned operation.

Examples:
input:
3
4
0 1 0 2
1 1 3
2
3 0
1
5
2 5 3 9 6
3 1 5 2
output:
1
3
6

Note: In the first test case, the following sequence of operations is possible:

  * perform the operation on $v=3$, then the values on the vertices will be $[0, 1, 1, 1]$;    * perform the operation on $v=1$, then the values on the vertices will be $[1, 0, 0, 0]$.

Buggy Code:
#include<bits/stdc++.h>

#define ll long long
#define F first
#define S second
#define mp make_pair
#define pb push_back

ll gcd(ll a, ll b)
{
    if (a == 0)
        return b;
    if (b == 0)
        return a;

    if (a == b)
        return a;

    if (a > b)
        return gcd(a - b, b);
    return gcd(a, b - a);
}

using namespace std;

ll dfs(vector<ll> &a, vector<vector<int> > childs, int node) {

    for(int i = 0; i < childs[node].size(); i++) {
        a[node] = ((a[node] + dfs(a, childs, childs[node][i])) / 2);
    }

    return a[node];

}

int main() {

    ios::sync_with_stdio(false);
    cin.tie(0);
    int t;
    cin >> t;

    while(t--) {
        int n;
        cin >> n;
        vector<ll> a(n + 1);

        for(int i = 1; i <= n; i++)
            cin >> a[i];

        vector<vector<int > > childs(n + 1);

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

        ll ans = INT_MAX;

        for(int i = 0; i < childs[1].size(); i++) {
            dfs(a, childs, childs[1][i]);
        }
        for(int i = 0; i < childs[1].size(); i++) {
            ans = min(ans, a[childs[1][i]]);
        }
        cout << ans + a[1] << '\n';
        // ll ans = 0;
        // cout << ans << '\n';

    }

}

/*
RILY <3
NEVER GIVE UP!!!
1
3
6
*/

**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
0 1 0 2
1 1 3
```


**Task:**
Generate a challenging test input that exposes the bug in the buggy code of the algorithm problem:
Algorithm Problem:
Title: Maximize the Root
time_limit_ms: 3000
memory_limit_mb: 256
Description: You are given a rooted tree, consisting of $n$ vertices. The vertices in the tree are numbered from $1$ to $n$, and the root is the vertex $1$. The value $a_i$ is written at the $i$-th vertex.

You can perform the following operation any number of times (possibly zero): choose a vertex $v$ which has at least one child; increase $a_v$ by $1$; and decrease $a_u$ by $1$ for all vertices $u$ that are in the subtree of $v$ (except $v$ itself). However, after each operation, the values on all vertices should be non-negative.

Your task is to calculate the maximum possible value written at the root using the aforementioned operation.

Input: The first line contains a single integer $t$ ($1 \le t \le 10^4$) — the number of test cases.

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

The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($0 \le a_i \le 10^9$) — the initial values written at vertices.

The third line contains $n-1$ integers $p_2, p_3, \dots, p_n$ ($1 \le p_i \le n$), where $p_i$ is the parent of the $i$-th vertex in the tree. Vertex $1$ is the root.

Additional constraint on the input: the sum of $n$ over all test cases doesn't exceed $2 \cdot 10^5$.

Output: For each test case, print a single integer — the maximum possible value written at the root using the aforementioned operation.

Examples:
input:
3
4
0 1 0 2
1 1 3
2
3 0
1
5
2 5 3 9 6
3 1 5 2
output:
1
3
6

Note: In the first test case, the following sequence of operations is possible:

  * perform the operation on $v=3$, then the values on the vertices will be $[0, 1, 1, 1]$;    * perform the operation on $v=1$, then the values on the vertices will be $[1, 0, 0, 0]$.

Buggy Code:
def dfs_modif(root): # pass in the vertices idx (0 indexed)
    global cur
    found = False
    for idx in range(n-1):
        if parents[idx] == root+1:
            dfs_modif(idx+1)
            found = True

    if found:
        if values[root] < cur:
            cur = values[root] + (cur - values[root])//2

    else:
        cur = values[root]

    return cur

t = int(input())
for _ in range(t):
    n = int(input()) # number of vertices
    values = list(map(int, input().split(" ")))
    parents = list(map(int, input().split(" ")))
    vis = [False] * n
    res = float('inf')
    for idx in range(n-1):
        cur = float('inf')
        if parents[idx] == 1:
            res = min(res, dfs_modif(idx+1))

    if res == float('inf'):
        print(values[0])
    else:
        print(values[0] + res)

**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
0 0 0 0
1 1 1
2
1 0
1
5
10 10 10 10 10
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: Maximize the Root
time_limit_ms: 3000
memory_limit_mb: 256
Description: You are given a rooted tree, consisting of $n$ vertices. The vertices in the tree are numbered from $1$ to $n$, and the root is the vertex $1$. The value $a_i$ is written at the $i$-th vertex.

You can perform the following operation any number of times (possibly zero): choose a vertex $v$ which has at least one child; increase $a_v$ by $1$; and decrease $a_u$ by $1$ for all vertices $u$ that are in the subtree of $v$ (except $v$ itself). However, after each operation, the values on all vertices should be non-negative.

Your task is to calculate the maximum possible value written at the root using the aforementioned operation.

Input: The first line contains a single integer $t$ ($1 \le t \le 10^4$) — the number of test cases.

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

The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($0 \le a_i \le 10^9$) — the initial values written at vertices.

The third line contains $n-1$ integers $p_2, p_3, \dots, p_n$ ($1 \le p_i \le n$), where $p_i$ is the parent of the $i$-th vertex in the tree. Vertex $1$ is the root.

Additional constraint on the input: the sum of $n$ over all test cases doesn't exceed $2 \cdot 10^5$.

Output: For each test case, print a single integer — the maximum possible value written at the root using the aforementioned operation.

Examples:
input:
3
4
0 1 0 2
1 1 3
2
3 0
1
5
2 5 3 9 6
3 1 5 2
output:
1
3
6

Note: In the first test case, the following sequence of operations is possible:

  * perform the operation on $v=3$, then the values on the vertices will be $[0, 1, 1, 1]$;    * perform the operation on $v=1$, then the values on the vertices will be $[1, 0, 0, 0]$.

Buggy Code:
from types import GeneratorType
from math import inf
import sys

# 提高最大递归深度限制
sys.setrecursionlimit(2 * (10 ** 5))

def bootstrap(f, stack=None):
    if stack is None:
        stack = []

    def func(*args, **kwargs):
        if stack:
            return f(*args, **kwargs)
        else:
            to = f(*args, **kwargs)
            while True:
                if type(to) is GeneratorType:
                    stack.append(to)
                    to = next(to)
                else:
                    stack.pop()
                    if not stack:
                        break
                    to = stack[-1].send(to)
            return to

    return func
def cf1997D():
    n = int(input())
    a = list(map(int, input().split()))
    g = [[] for _ in range(n)]
    b = list(map(int, input().split()))
    for i, x in enumerate(b):
        i += 1
        x -= 1
        g[x].append(i)

    # @bootstrap
    def dfs(x: int, f: int) -> int:

        # 先获取儿子的最小值
        mn = inf
        for y in g[x]:
            if y == f:
                continue
            cur = dfs(y, x)
            mn = min(cur, mn)
        if mn == inf:
            return a[x]
        if x != 0:
            if mn > a[x]:
                return (mn + a[x]) >> 1
            else:
                return mn
        else:
            return mn + a[x]

    ans = dfs(0, -1)
    print(ans)
    return

t = int(input())
for i in range(t):
    cf1997D()

**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 buggy code, we need to consider edge cases and scenarios that are likely to cause issues. The key points to focus on are:

1. **Trees with deep hierarchies**: This can cause issues with recursion depth and potentially lead to incorrect calculations.
2. **Large values in the tree nodes**: Large values can cause overflow or incorrect calculations.
3. **Trees with complex structures**: Trees with multiple levels of branching can expose bugs in the DFS traversal and calculations.
4. **Cases where the root value is already large**: This can help in testing the correctness of the algorithm when the initial value at the root is already high.

Given these points, let's create a small-scale test input that is complete and valid:

```plaintext
1
5
1000000000 1000000000 1000000000 1000000000 1000000000
1 1 3 3
```

### Explanation:
- **Number of test cases**: 1
- **Number of vertices**: 5
- **Initial values at vertices**: All values are set to a very large number (1,000,000,000) to test the algorithm's ability to handle large values.
- **Parent array**: The tree structure is as follows:
  - Vertex 1 (root) has children 2 and 3.
  - Vertex 3 has children 4 and 5.

This test case is designed to:
- Ensure the algorithm can handle large values.
- Test the DFS traversal and calculations in a tree with a simple but non-trivial structure.
- Check if the algorithm correctly handles the root value and the operations on its children.

This input should help expose any bugs in the given buggy code.


**Task:**
Generate a challenging test input that exposes the bug in the buggy code of the algorithm problem:
Algorithm Problem:
Title: Maximize the Root
time_limit_ms: 3000
memory_limit_mb: 256
Description: You are given a rooted tree, consisting of $n$ vertices. The vertices in the tree are numbered from $1$ to $n$, and the root is the vertex $1$. The value $a_i$ is written at the $i$-th vertex.

You can perform the following operation any number of times (possibly zero): choose a vertex $v$ which has at least one child; increase $a_v$ by $1$; and decrease $a_u$ by $1$ for all vertices $u$ that are in the subtree of $v$ (except $v$ itself). However, after each operation, the values on all vertices should be non-negative.

Your task is to calculate the maximum possible value written at the root using the aforementioned operation.

Input: The first line contains a single integer $t$ ($1 \le t \le 10^4$) — the number of test cases.

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

The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($0 \le a_i \le 10^9$) — the initial values written at vertices.

The third line contains $n-1$ integers $p_2, p_3, \dots, p_n$ ($1 \le p_i \le n$), where $p_i$ is the parent of the $i$-th vertex in the tree. Vertex $1$ is the root.

Additional constraint on the input: the sum of $n$ over all test cases doesn't exceed $2 \cdot 10^5$.

Output: For each test case, print a single integer — the maximum possible value written at the root using the aforementioned operation.

Examples:
input:
3
4
0 1 0 2
1 1 3
2
3 0
1
5
2 5 3 9 6
3 1 5 2
output:
1
3
6

Note: In the first test case, the following sequence of operations is possible:

  * perform the operation on $v=3$, then the values on the vertices will be $[0, 1, 1, 1]$;    * perform the operation on $v=1$, then the values on the vertices will be $[1, 0, 0, 0]$.

Buggy Code:
import io
import sys
from collections import defaultdict, deque, Counter
from itertools import permutations, combinations, accumulate
from heapq import heappush, heappop
from bisect import bisect_right, bisect_left
from math import gcd
import math

_INPUT = """\
6
3
4
0 1 0 2
1 1 3
2
3 0
1
5
2 5 3 9 6
3 1 5 2
"""

def input():
  return sys.stdin.readline()[:-1]

def solve(test):
  t=int(input())
  for _ in range(t):
    n=int(input())
    a=list(map(int, input().split()))
    p=list(map(lambda x:int(x)-1, input().split()))
    g=[[] for _ in range(n)]
    for i in range(n-1):
      g[i+1].append(p[i])
      g[p[i]].append(i+1)
    l,r=0,sum(a)+1
    while r-l>1:
      m=(l+r)//2
      if a[0]>=m: l=m
      else:
        queue=[~0,0]
        done=[0]*n
        now=m-a[0]
        d=[None]*n
        flg=0
        while queue:
          v=queue.pop()
          if v>=0:
            done[v]=1
            if a[v]<now:
              if v==0:
                d[0]=now
              else:
                d[v]=now-a[v]
                now+=d[v]
              if len(g[v])==1 and g[v][0]==p[v-1]:
                flg=1
                break
            else:
              d[v]=0
            for u in g[v]:
              if not done[u]:
                queue.append(~u)
                queue.append(u)
          else:
            now-=d[~v]
        if flg==0: l=m
        else: r=m
    print(l)

def random_input():
  from random import randint,shuffle
  N=randint(1,10)
  M=randint(1,N)
  A=list(range(1,M+1))+[randint(1,M) for _ in range(N-M)]
  shuffle(A)
  return (" ".join(map(str, [N,M]))+"\n"+" ".join(map(str, A))+"\n")*3

def simple_solve():
  return []

def main(test):
  if test==0:
    solve(0)
  elif test==1:
    sys.stdin = io.StringIO(_INPUT)
    case_no=int(input())
    for _ in range(case_no):
      solve(0)
  else:
    for i in range(1000):
      sys.stdin = io.StringIO(random_input())
      x=solve(1)
      y=simple_solve()
      if x!=y:
        print(i,x,y)
        print(*[line for line in sys.stdin],sep='')
        break

#0:提出用、1:与えられたテスト用、2:ストレステスト用
main(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 generate a challenging test input that exposes the bug in the provided buggy code, we need to focus on edge cases and scenarios that are likely to cause issues. Here are the steps to create such a test input:

1. **Tree Structure**: Ensure the tree structure is complex enough to test the algorithm's ability to handle multiple levels of children and grandchildren.
2. **Initial Values**: Use initial values that are likely to cause the algorithm to make incorrect decisions, such as very high values in child nodes and very low values in the root.
3. **Operations**: Consider cases where the operations can be performed multiple times, but the values need to be carefully managed to avoid negative values.

Given these considerations, let's construct a test input:

### Test Input
```plaintext
3
4
0 1000000000 0 2
1 1 3
2
3 0
1
5
2 5 3 9 6
3 1 5 2
```

### Explanation:
1. **Test Case 1**:
   - **Tree Structure**: The tree has 4 vertices with the root at vertex 1.
   - **Initial Values**: The values are [0, 1000000000, 0, 2].
   - **Parent Array**: The parent array is [1, 1, 3], indicating the following structure:
     - Vertex 1 has children 2 and 3.
     - Vertex 3 has a child 4.
   - **Challenge**: The high value at vertex 2 (1000000000) and the low value at the root (0) should test the algorithm's ability to distribute values correctly.

2. **Test Case 2**:
   - **Tree Structure**: The tree has 2 vertices with the root at vertex 1.
   - **Initial Values**: The values are [3, 0].
   - **Parent Array**: The parent array is [1], indicating that vertex 2 is a child of vertex 1.
   - **Challenge**: The low value at vertex 2 (0) and the high value at the root (3) should test the algorithm's ability to handle small trees.

3. **Test Case 3**:
   - **Tree Structure**: The tree has 5 vertices with the root at vertex 1.
   - **Initial Values**: The values are [2, 5, 3, 9, 6].
   - **Parent Array**: The parent array is [3, 1, 5, 2], indicating the following structure:
     - Vertex 1 has children 2 and 3.
     - Vertex 2 has a child 4.
     - Vertex 3 has a child 5.
   - **Challenge**: The various values and the structure should test the algorithm's ability to handle more complex trees with multiple levels.

This test input should help expose any bugs in the buggy code by challenging its ability to handle different tree structures and initial values.


**Task:**
Generate a challenging test input that exposes the bug in the buggy code of the algorithm problem:
Algorithm Problem:
Title: Maximize the Root
time_limit_ms: 3000
memory_limit_mb: 256
Description: You are given a rooted tree, consisting of $n$ vertices. The vertices in the tree are numbered from $1$ to $n$, and the root is the vertex $1$. The value $a_i$ is written at the $i$-th vertex.

You can perform the following operation any number of times (possibly zero): choose a vertex $v$ which has at least one child; increase $a_v$ by $1$; and decrease $a_u$ by $1$ for all vertices $u$ that are in the subtree of $v$ (except $v$ itself). However, after each operation, the values on all vertices should be non-negative.

Your task is to calculate the maximum possible value written at the root using the aforementioned operation.

Input: The first line contains a single integer $t$ ($1 \le t \le 10^4$) — the number of test cases.

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

The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($0 \le a_i \le 10^9$) — the initial values written at vertices.

The third line contains $n-1$ integers $p_2, p_3, \dots, p_n$ ($1 \le p_i \le n$), where $p_i$ is the parent of the $i$-th vertex in the tree. Vertex $1$ is the root.

Additional constraint on the input: the sum of $n$ over all test cases doesn't exceed $2 \cdot 10^5$.

Output: For each test case, print a single integer — the maximum possible value written at the root using the aforementioned operation.

Examples:
input:
3
4
0 1 0 2
1 1 3
2
3 0
1
5
2 5 3 9 6
3 1 5 2
output:
1
3
6

Note: In the first test case, the following sequence of operations is possible:

  * perform the operation on $v=3$, then the values on the vertices will be $[0, 1, 1, 1]$;    * perform the operation on $v=1$, then the values on the vertices will be $[1, 0, 0, 0]$.

Buggy Code:
import java.util.ArrayList;
import java.util.Scanner;

public class Uzumaki_Naruto {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int t = sc.nextInt();
        for (int tt = 0; tt < t; tt++) {

            int n = sc.nextInt();
            long arr[] = new long[n + 1];
            for (int i = 1; i < n + 1; i++) {
                arr[i] = sc.nextLong();
            }
            // System.out.println(Arrays.toString(arr));

            int parent[] = new int[n - 1];
            for (int i = 0; i < n - 1; i++) {
                parent[i] = sc.nextInt();
            }

            ArrayList<ArrayList<Integer>> graph = new ArrayList<>();

            for (int i = 0; i < n + 1; i++) {
                graph.add(new ArrayList<>());
            }

            for (int i = 0; i < n - 1; i++) {
                graph.get(parent[i]).add(i + 2);
                graph.get(i + 2).add(parent[i]);
            }

            //System.out.println(graph);

            long ans = helper(graph, arr, 1, -1);
            System.out.println(ans);

        }
        sc.close();
    }

    public static long helper(ArrayList<ArrayList<Integer>> graph, long arr[], int node, int parent) {
        long min = Long.MAX_VALUE;
        for (int child : graph.get(node)) {
            if (child == parent) {
                continue;
            }
            min = Math.min(helper(graph, arr, child, node), min);
        }

        if (min == Long.MAX_VALUE) {
            return arr[node];
        }

        if (min <= arr[node]) {
            if (node == 1) {
                return arr[node];
            }
            return min;
        } else {
            if (node == 1) {
                return arr[node] + min;
            } else {
                return (min + arr[node]) / 2;
            }
        }
    }
}

**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
0 1 0 2
1 1 3
2
3 0
1
5
2 5 3 9 6
3 1 5 2
```


**Task:**
Generate a challenging test input that exposes the bug in the buggy code of the algorithm problem:
Algorithm Problem:
Title: Maximize the Root
time_limit_ms: 3000
memory_limit_mb: 256
Description: You are given a rooted tree, consisting of $n$ vertices. The vertices in the tree are numbered from $1$ to $n$, and the root is the vertex $1$. The value $a_i$ is written at the $i$-th vertex.

You can perform the following operation any number of times (possibly zero): choose a vertex $v$ which has at least one child; increase $a_v$ by $1$; and decrease $a_u$ by $1$ for all vertices $u$ that are in the subtree of $v$ (except $v$ itself). However, after each operation, the values on all vertices should be non-negative.

Your task is to calculate the maximum possible value written at the root using the aforementioned operation.

Input: The first line contains a single integer $t$ ($1 \le t \le 10^4$) — the number of test cases.

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

The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($0 \le a_i \le 10^9$) — the initial values written at vertices.

The third line contains $n-1$ integers $p_2, p_3, \dots, p_n$ ($1 \le p_i \le n$), where $p_i$ is the parent of the $i$-th vertex in the tree. Vertex $1$ is the root.

Additional constraint on the input: the sum of $n$ over all test cases doesn't exceed $2 \cdot 10^5$.

Output: For each test case, print a single integer — the maximum possible value written at the root using the aforementioned operation.

Examples:
input:
3
4
0 1 0 2
1 1 3
2
3 0
1
5
2 5 3 9 6
3 1 5 2
output:
1
3
6

Note: In the first test case, the following sequence of operations is possible:

  * perform the operation on $v=3$, then the values on the vertices will be $[0, 1, 1, 1]$;    * perform the operation on $v=1$, then the values on the vertices will be $[1, 0, 0, 0]$.

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

public class D {

    public static void main(String[] args) throws IOException {
        InputReader in = new InputReader(System.in);
        PrintWriter out = new PrintWriter(System.out);
        Solve solve = new Solve(in, out);
        solve.solve();
        out.close();
    }

    static class InputReader {
        public BufferedReader reader;
        public StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream), 32768);
            tokenizer = null;
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

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

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

        public double nextDouble() {
            return Double.parseDouble(next());
        }
    }

    private static class Solve {
        private final PrintWriter out;
        private final InputReader in;

        public Solve(InputReader in, PrintWriter out) {
            this.in = in;
            this.out = out;
        }

        public void solve() {
            int t = in.nextInt();
            while (t --> 0) {
                solve_inner();
            }
        }

        int n;
        Map<Integer, List<Integer>> graph;
        long[] a;
        long[] f;
        long[] m;

        public long calc(int v) {
            List<Integer> children = graph.get(v);
            if (children == null) {
                f[v] = a[v];
                m[v] = a[v];
                return a[v];
            }

            long min = Long.MAX_VALUE;
            long gm = Long.MAX_VALUE;
            for (Integer child : children) {
                min = Math.min(min, calc(child));
                gm = Math.min(gm, m[child]);
            }
            m[v] = gm;
            long d = Math.min(m[v], Math.max(0, (a[v] + min) / 2 - a[v]));
            for (Integer child : children) {
                f[child] -= d;
                if (f[child] < 0) throw new RuntimeException();
            }
            f[v] = a[v] + d;
            m[v] = Math.min(min, f[v]);
            return f[v];
        }

        private void solve_inner() {
            n = in.nextInt();
            graph = new HashMap<>();
            a = new long[n + 1];
            f = new long[n + 1];
            m = new long[n + 1];
            for (int i = 1; i <= n; i++) {
                a[i] = in.nextLong();
            }
            for (int i = 2; i <= n; i++) {
                int p = in.nextInt();
                List<Integer> v = graph.get(p);
                if (v == null) {
                    v = new ArrayList<>();
                }
                v.add(i);
                graph.put(p, v);
            }

            calc(1);
//            out.println(Arrays.toString(f));
//            out.println(Arrays.toString(m));
            long min = Long.MAX_VALUE;
            for (int i = 2; i <= n; i++) {
                min = Math.min(min, f[i]);
            }
            out.println(f[1] + min);
        }
    }
}

**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 code, we need to focus on edge cases that can cause the algorithm to fail. One such edge case is when the tree has a structure that causes the minimum values to be distributed in a way that the algorithm's logic for calculating the maximum possible value at the root fails.

Here's a small-scale test input that can expose the bug:

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

Explanation:
- The tree has 5 vertices.
- The values at the vertices are: `1, 2, 3, 4, 5`.
- The parent-child relationships are:
  - Vertex 2 and 3 are children of vertex 1.
  - Vertex 4 and 5 are children of vertex 3.

This structure ensures that the root (vertex 1) has two children (vertices 2 and 3), and vertex 3 has two children (vertices 4 and 5). The values are increasing as we move down the tree, which can cause the algorithm to miscalculate the maximum possible value at the root.

Let's break down the expected behavior:
1. The initial values are: `[1, 2, 3, 4, 5]`.
2. The tree structure is:
   - 1 (1) -> 2 (2)
   - 1 (1) -> 3 (3)
   - 3 (3) -> 4 (4)
   - 3 (3) -> 5 (5)

The goal is to maximize the value at the root (vertex 1). The optimal operations would be to transfer values from the deeper nodes (4 and 5) to the root. However, the given code might not handle this correctly due to its logic for calculating the minimum values and distributing the changes.

This test input should help expose any issues in the algorithm's logic for handling the distribution of values and the calculation of the maximum possible value at the root.


**Task:**
Generate a challenging test input that exposes the bug in the buggy code of the algorithm problem:
Algorithm Problem:
Title: Maximize the Root
time_limit_ms: 3000
memory_limit_mb: 256
Description: You are given a rooted tree, consisting of $n$ vertices. The vertices in the tree are numbered from $1$ to $n$, and the root is the vertex $1$. The value $a_i$ is written at the $i$-th vertex.

You can perform the following operation any number of times (possibly zero): choose a vertex $v$ which has at least one child; increase $a_v$ by $1$; and decrease $a_u$ by $1$ for all vertices $u$ that are in the subtree of $v$ (except $v$ itself). However, after each operation, the values on all vertices should be non-negative.

Your task is to calculate the maximum possible value written at the root using the aforementioned operation.

Input: The first line contains a single integer $t$ ($1 \le t \le 10^4$) — the number of test cases.

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

The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($0 \le a_i \le 10^9$) — the initial values written at vertices.

The third line contains $n-1$ integers $p_2, p_3, \dots, p_n$ ($1 \le p_i \le n$), where $p_i$ is the parent of the $i$-th vertex in the tree. Vertex $1$ is the root.

Additional constraint on the input: the sum of $n$ over all test cases doesn't exceed $2 \cdot 10^5$.

Output: For each test case, print a single integer — the maximum possible value written at the root using the aforementioned operation.

Examples:
input:
3
4
0 1 0 2
1 1 3
2
3 0
1
5
2 5 3 9 6
3 1 5 2
output:
1
3
6

Note: In the first test case, the following sequence of operations is possible:

  * perform the operation on $v=3$, then the values on the vertices will be $[0, 1, 1, 1]$;    * perform the operation on $v=1$, then the values on the vertices will be $[1, 0, 0, 0]$.

Buggy Code:
import sys
input = lambda :sys.stdin.readline()[:-1]
ni = lambda :int(input())
na = lambda :list(map(int,input().split()))
yes = lambda :print("yes");Yes = lambda :print("Yes");YES = lambda : print("YES")
no = lambda :print("no");No = lambda :print("No");NO = lambda : print("NO")
#######################################################################

for _ in range(ni()):
    n = ni()
    a = na()
    p = [-1] + [x- 1 for x in na()]
    g = [[] for i in range(n)]
    for i in range(1, n):
        g[p[i]].append(i)

    et = []
    st = [0]
    seen = [0] * n
    seen[0] = 1
    chi = [[] for i in range(n)]
    while st:
        x = st.pop()
        et.append(x)
        for y in g[x]:
            if not seen[y]:
                seen[y] = 1
                st.append(y)
                chi[x].append(y)

    dp = [-1] * n
    for i in et[::-1]:
        if len(chi[i]) == 0:
            dp[i] = a[i]
        else:
            f = [dp[j] for j in chi[i]]
            z = min(f)
            if z <= a[i]:
                dp[i] = a[i]
            else:
                dp[i] = a[i] + z >> 1
    print(a[0] + min([dp[i] for i in chi[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
3
2
1 0
1
4
0 1 0 2
1 1 3
5
2 5 3 9 6
3 1 5 2
```


**Task:**
Generate a challenging test input that exposes the bug in the buggy code of the algorithm problem:
Algorithm Problem:
Title: Maximize the Root
time_limit_ms: 3000
memory_limit_mb: 256
Description: You are given a rooted tree, consisting of $n$ vertices. The vertices in the tree are numbered from $1$ to $n$, and the root is the vertex $1$. The value $a_i$ is written at the $i$-th vertex.

You can perform the following operation any number of times (possibly zero): choose a vertex $v$ which has at least one child; increase $a_v$ by $1$; and decrease $a_u$ by $1$ for all vertices $u$ that are in the subtree of $v$ (except $v$ itself). However, after each operation, the values on all vertices should be non-negative.

Your task is to calculate the maximum possible value written at the root using the aforementioned operation.

Input: The first line contains a single integer $t$ ($1 \le t \le 10^4$) — the number of test cases.

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

The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($0 \le a_i \le 10^9$) — the initial values written at vertices.

The third line contains $n-1$ integers $p_2, p_3, \dots, p_n$ ($1 \le p_i \le n$), where $p_i$ is the parent of the $i$-th vertex in the tree. Vertex $1$ is the root.

Additional constraint on the input: the sum of $n$ over all test cases doesn't exceed $2 \cdot 10^5$.

Output: For each test case, print a single integer — the maximum possible value written at the root using the aforementioned operation.

Examples:
input:
3
4
0 1 0 2
1 1 3
2
3 0
1
5
2 5 3 9 6
3 1 5 2
output:
1
3
6

Note: In the first test case, the following sequence of operations is possible:

  * perform the operation on $v=3$, then the values on the vertices will be $[0, 1, 1, 1]$;    * perform the operation on $v=1$, then the values on the vertices will be $[1, 0, 0, 0]$.

Buggy Code:
#from math import ceil,log
#from collections import deque,Counter
#from bisect import bisect
#from heapq import heappush,heappop
#from random import randint

from sys import stdin,stdout
input=lambda:stdin.readline().rstrip()
print=lambda *x,sep=' ',end='\n':stdout.write(sep.join(map(str,x))+end)

from types import GeneratorType
def bootstrap(f, stack=[]):
    def wrappedfunc(*args, **kwargs):
        if stack:
            return f(*args, **kwargs)
        else:
            to = f(*args, **kwargs)
            while True:
                if type(to) is GeneratorType:
                    stack.append(to)
                    to = next(to)
                else:
                    stack.pop()
                    if not stack:
                        break
                    to = stack[-1].send(to)
            return to
    return wrappedfunc

def out(l):
    print(' '.join(map(str,l)))

def yes():
    print('Yes')

def no():
    print('No')

def alice():
    print('Alice')

def bob():
    print('Bob')

@bootstrap
def dfs(par,grand_par=0):
    mi=float('inf')
    for i,child in enumerate(adj[par]):
        if child!=grand_par:
            yield dfs(child,par)
            mi=min(mi,a[child])
    if grand_par==0:
        yield
    ori=a[par]
    if mi!=float('inf'):
        a[par]=(a[par]+mi)//2
    diff=a[par]-ori
    for i,child in enumerate(adj[par]):
        if child!=grand_par:
            a[child]-=diff
    yield

def solve():
    global adj,a
    n=int(input())
    a=[0]+list(map(int,input().split()))
    p=[0,0]+list(map(int,input().split()))
    adj=[[] for i in range(n+1)]
    for i in range(2,n+1):
        adj[p[i]].append(i)
        adj[i].append(p[i])
    #print(adj)
    ans=a[1]
    dfs(1)
    print(ans+min(a[2:]))

for _ in range(int(input())):
    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
3
4
1 1 1 1
1 1 1
2
1 1
1
5
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: Maximize the Root
time_limit_ms: 3000
memory_limit_mb: 256
Description: You are given a rooted tree, consisting of $n$ vertices. The vertices in the tree are numbered from $1$ to $n$, and the root is the vertex $1$. The value $a_i$ is written at the $i$-th vertex.

You can perform the following operation any number of times (possibly zero): choose a vertex $v$ which has at least one child; increase $a_v$ by $1$; and decrease $a_u$ by $1$ for all vertices $u$ that are in the subtree of $v$ (except $v$ itself). However, after each operation, the values on all vertices should be non-negative.

Your task is to calculate the maximum possible value written at the root using the aforementioned operation.

Input: The first line contains a single integer $t$ ($1 \le t \le 10^4$) — the number of test cases.

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

The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($0 \le a_i \le 10^9$) — the initial values written at vertices.

The third line contains $n-1$ integers $p_2, p_3, \dots, p_n$ ($1 \le p_i \le n$), where $p_i$ is the parent of the $i$-th vertex in the tree. Vertex $1$ is the root.

Additional constraint on the input: the sum of $n$ over all test cases doesn't exceed $2 \cdot 10^5$.

Output: For each test case, print a single integer — the maximum possible value written at the root using the aforementioned operation.

Examples:
input:
3
4
0 1 0 2
1 1 3
2
3 0
1
5
2 5 3 9 6
3 1 5 2
output:
1
3
6

Note: In the first test case, the following sequence of operations is possible:

  * perform the operation on $v=3$, then the values on the vertices will be $[0, 1, 1, 1]$;    * perform the operation on $v=1$, then the values on the vertices will be $[1, 0, 0, 0]$.

Buggy Code:
#include <bits/stdc++.h>

#define ll long long
#define int long long
#define pi pair<int,int>
#define vi vector<int>
#define vvi vector <vector <int>>
const int mod = 1e9 + 7;

using namespace std;

int gcd(int a, int b){
    //a>b
    if(b==0) return a;
    return gcd(b,a%b);
}
istream &operator>>(istream &is, vector<int> &vec)
{
//    vec.clear();
    int num;
    while (is >> num)
    {
        vec.push_back(num);
        char ch = is.peek();
        if (ch == '\n')
        {
            is.ignore();
            break;
        }
    }
    return is;
}

void print(vector <int> v){
    for(auto it:v) cout << it <<' ';
    cout <<endl;
}
vector<int> prefixSum(vector<int> v ){
    vector<int> ans;
    int sum=0;
    for (int i =0; i < v.size();i++){
        sum+=v[i];
        ans.push_back(sum);
    }
    return ans;
}
void print(const vector<std::vector<int>> arr) {
    for (const std::vector<int>& row : arr) {
        for (int num : row) {

            std::cout << num << " ";
        }
        std::cout << std::endl;
    }
}

bool poss(int r, int node, vvi & adj, vi & a){
    int val = a[node]-r;

    if(val < 0 && node != 0){
        r-=val;
        if( adj[node].empty()) return false;
    }

    for(int it : adj[node]){
        if( !poss(r, it, adj, a)) return false;
    }

    return true;
}

void solve(){
    ll n;
    vi a ,p;
    string s;
    cin >>n >> a >> p;

    vector <vector <int>> adj(n);
    for(int i = 0 ; i < n-1; i++){
        adj[--p[i]].push_back(i+1);
    }

    int ans =0, h= 1e17, l =0;

    while(l <=h ){
        int m = (l+h)/2;
        if(poss(m, 0, adj, a)){
//            cout <<"poss for m = "<<m <<endl;
            ans = m;
            l=m+1;
        }else{
            h=m -1;
        }
    }

//    print (adj);
//    cout <<"---------------"<<endl;

    cout << a[0]+ans <<endl;

}

int32_t main()
{

    ios_base ::sync_with_stdio(false);
    cin.tie(NULL);

#ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
#endif

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

    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 generate a challenging test input that exposes the bug in the provided buggy code, we need to consider edge cases and scenarios that might cause the algorithm to fail. Here are the steps to think through this:

1. **Understand the Bug**: The buggy code seems to have issues with the binary search and the `poss` function, which checks if a certain value can be achieved at the root. The main issue might be in how it handles the subtree values and the propagation of the operation effects.

2. **Edge Cases**:
   - **Tree with a single child**: This can test if the algorithm correctly handles simple trees.
   - **Tree with multiple levels**: This can test if the algorithm correctly handles more complex trees.
   - **Tree with large values**: This can test if the algorithm handles large numbers correctly.
   - **Tree with negative values**: Although the problem specifies non-negative values, it's good to test if the algorithm handles unexpected negative values gracefully.

3. **Small-Scale Test Input**: Since the output length is limited, we should focus on a small-scale input that is complete and valid.

Given these considerations, let's create a test input that might expose the bug:

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

### Explanation:
- **Number of Test Cases**: 1
- **Number of Vertices**: 4
- **Initial Values**: [1, 2, 3, 4]
- **Parent Array**: [1, 1, 2]

This input represents a tree with the following structure:
```
    1
   / \
  2   3
     /
    4
```

### Why This Input is Challenging:
- **Initial Values**: The values are increasing, which can make it difficult for the algorithm to handle the propagation of the operation effects correctly.
- **Tree Structure**: The tree has multiple levels, which can test the algorithm's ability to handle deeper subtrees.

This input should help expose any issues in the binary search and the `poss` function, especially in how it handles the propagation of the operation effects through the tree.


**Task:**
Generate a challenging test input that exposes the bug in the buggy code of the algorithm problem:
Algorithm Problem:
Title: Maximize the Root
time_limit_ms: 3000
memory_limit_mb: 256
Description: You are given a rooted tree, consisting of $n$ vertices. The vertices in the tree are numbered from $1$ to $n$, and the root is the vertex $1$. The value $a_i$ is written at the $i$-th vertex.

You can perform the following operation any number of times (possibly zero): choose a vertex $v$ which has at least one child; increase $a_v$ by $1$; and decrease $a_u$ by $1$ for all vertices $u$ that are in the subtree of $v$ (except $v$ itself). However, after each operation, the values on all vertices should be non-negative.

Your task is to calculate the maximum possible value written at the root using the aforementioned operation.

Input: The first line contains a single integer $t$ ($1 \le t \le 10^4$) — the number of test cases.

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

The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($0 \le a_i \le 10^9$) — the initial values written at vertices.

The third line contains $n-1$ integers $p_2, p_3, \dots, p_n$ ($1 \le p_i \le n$), where $p_i$ is the parent of the $i$-th vertex in the tree. Vertex $1$ is the root.

Additional constraint on the input: the sum of $n$ over all test cases doesn't exceed $2 \cdot 10^5$.

Output: For each test case, print a single integer — the maximum possible value written at the root using the aforementioned operation.

Examples:
input:
3
4
0 1 0 2
1 1 3
2
3 0
1
5
2 5 3 9 6
3 1 5 2
output:
1
3
6

Note: In the first test case, the following sequence of operations is possible:

  * perform the operation on $v=3$, then the values on the vertices will be $[0, 1, 1, 1]$;    * perform the operation on $v=1$, then the values on the vertices will be $[1, 0, 0, 0]$.

Buggy Code:
//Abhinav garg

#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
#define int                 long long int
#define ld                 long double
#define fps(x,y)           fixed << setprecision(y) << x
#define loop(i,a,n)        for(int i=a;i<=n;i++)
#define set_bits           __builtin_popcountll
#define sz(x)              ((int)(x).size())
#define rev(j,a,n)         for(int j=a;j>=n;j--)
#define it(i,v)            for(auto i=v.begin();i!=v.end();i++)
#define pb                 push_back
#define vi                 vector
#define all(v)             v.begin(),v.end()
#define pr                 pair<int, int>
#define ff                 first
#define ss                 second
#define ump                unordered_map
#define ordered_set tree<pr, null_type,less<pr>, rb_tree_tag,tree_order_statistics_node_update>
using namespace std;
using namespace __gnu_pbds;

const int mod=1000000007;

#ifndef ONLINE_JUDGE
#define debug(x) cerr << #x <<" "; _print(x); cerr << endl;
#else
#define debug(x);
#endif

void _print(int t) {cerr << t;}
void _print(string t) {cerr << t;}
void _print(char t) {cerr << t;}
void _print(ld t) {cerr << t;}
void _print(double t) {cerr << t;}
void _print(unsigned int t) {cerr << t;}
void _print(bool t) {cerr << t;}

template <class T, class V> void _print(pair <T, V> p);
template <class T> void _print(vector <T> v);
template <class T> void _print(set <T> v);
template <class T, class V> void _print(map <T, V> v);
template <class T> void _print(multiset <T> v);
template <class T, class V> void _print(pair <T, V> p) {cerr << "{"; _print(p.ff); cerr << ","; _print(p.ss); cerr << "}";}
template <class T> void _print(vector <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";}
template <class T> void _print(set <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";}
template <class T> void _print(multiset <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";}
template <class T, class V> void _print(map <T, V> v) {cerr << "[ "; for (auto i : v) {_print(i); cerr << " ";} cerr << "]";}

inline void fastio() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
   #ifndef ONLINE_JUDGE
   freopen("inp.txt", "r", stdin);
   freopen("op.txt", "w", stdout);
   freopen("error.txt", "w", stderr);
   #endif
}

int n;

bool dfs(int node,int req, vi<vi<int>> &tr, vi<int> &a){
    bool poss = true;
    for(auto child:tr[node]){
        poss &= dfs(child, req + max(req - a[child],0LL), tr, a);
    }
    if(sz(tr[node]) == 0){
        return a[node] >= req;
    }
    return poss;

}

void test(){
    cin>>n;
    vi<int> a(n);
    loop(i,0,n-1) cin>>a[i];
    vi<vi<int>> tr(n);
    loop(i,1,n-1){
        int par; cin>>par;
        par--;
        tr[par].pb(i);
    }
    debug(tr);
    int ans = a[0];
    int l = a[0], r = 12;
    while(l<=r){
        int m = (l+r)>>1LL;
        if(dfs(0 ,m-a[0], tr, a)){
            ans = m;
            l = m+1;
        }
        else{
            r = m-1;
        }
    }
    cout<<ans<<"\n";

}

int32_t main(int32_t argc,char const *arg[]){
    fastio();
    int tc=1;
    //prime();
    cin>>tc;
    while(tc--){
        test();
    }

    return 0;
}
/* if (a|b)+(a&b) = (a+b)*/

**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
0 1 0 2
1 1 3
2
3 0
1
5
2 5 3 9 6
3 1 5 2
```


**Task:**
Generate a challenging test input that exposes the bug in the buggy code of the algorithm problem:
Algorithm Problem:
Title: Maximize the Root
time_limit_ms: 3000
memory_limit_mb: 256
Description: You are given a rooted tree, consisting of $n$ vertices. The vertices in the tree are numbered from $1$ to $n$, and the root is the vertex $1$. The value $a_i$ is written at the $i$-th vertex.

You can perform the following operation any number of times (possibly zero): choose a vertex $v$ which has at least one child; increase $a_v$ by $1$; and decrease $a_u$ by $1$ for all vertices $u$ that are in the subtree of $v$ (except $v$ itself). However, after each operation, the values on all vertices should be non-negative.

Your task is to calculate the maximum possible value written at the root using the aforementioned operation.

Input: The first line contains a single integer $t$ ($1 \le t \le 10^4$) — the number of test cases.

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

The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($0 \le a_i \le 10^9$) — the initial values written at vertices.

The third line contains $n-1$ integers $p_2, p_3, \dots, p_n$ ($1 \le p_i \le n$), where $p_i$ is the parent of the $i$-th vertex in the tree. Vertex $1$ is the root.

Additional constraint on the input: the sum of $n$ over all test cases doesn't exceed $2 \cdot 10^5$.

Output: For each test case, print a single integer — the maximum possible value written at the root using the aforementioned operation.

Examples:
input:
3
4
0 1 0 2
1 1 3
2
3 0
1
5
2 5 3 9 6
3 1 5 2
output:
1
3
6

Note: In the first test case, the following sequence of operations is possible:

  * perform the operation on $v=3$, then the values on the vertices will be $[0, 1, 1, 1]$;    * perform the operation on $v=1$, then the values on the vertices will be $[1, 0, 0, 0]$.

Buggy Code:
// Problem: D. Maximize the Root
// Contest: Codeforces - Educational Codeforces Round 168 (Rated for Div. 2)
// URL: https://codeforces.com/contest/1997/problem/D
// Memory Limit: 256 MB
// Time Limit: 3000 ms
// Author: Neil Chetty

import java.io.*;
import java.util.*;

public class Main {
  public static void main(String[] args) {
    int t = in.nextInt();
    while (t-- > 0) solve();
    out.flush();
  }

  private static void solve() {
    // WRITE CODE HERE
    int n = in.nextInt();
    int[] a = new int[n + 1];
    for (int i = 0; i < n; i++) a[i + 1] = in.nextInt();
    List<List<Integer>> store = new ArrayList<>();
    for (int i = 0; i <= n; i++) store.add(new ArrayList<>());
    for (int i = 1; i < n; i++) {
      int ok = in.nextInt();
      store.get(i + 1).add(ok);
      store.get(ok).add(i + 1);
    }
    long left = 0, right = (long) (1e17);
    while (left <= right) {
      long mid = left + (right - left) / 2;
      if (helper(store, 1, 0, 0, a, mid))
        left = mid + 1;
      else
        right = mid - 1;
    }
    out.println(right);
    // out.println(store);
    // out.println(helper(store, 1, 0, 0, a, 10));
  }

  private static boolean helper(
      List<List<Integer>> store, int current, int parent, long sum, int[] a, long k) {
    if (current != 1 && store.get(current).size() == 1)
      return a[current] >= sum;
    if (current == 1)
      sum += (a[current] >= k ? 0 : Math.abs(a[current] - k));
    else
      sum += (a[current] >= sum ? 0 : Math.abs(a[current] - sum));
    boolean result = true;
    for (int adj : store.get(current)) {
      if (adj == parent)
        continue;
      result &= helper(store, adj, current, sum, a, k);
    }
    return result;
  }

  // ALL PRE-WRITTEN HELPER FUNCTIONS
  static QuickReader in = new QuickReader();
  static PrintWriter out = new PrintWriter(System.out);
  private final static int MOD = (int) ((1e9) + 7);

  private static boolean[] primeFinder(int n) {
    boolean[] result = new boolean[n + 1];
    Arrays.fill(result, true);
    result[0] = false;
    result[1] = false;
    for (int i = 2; i * i <= n; i++) {
      if (!result[i])
        continue;
      for (int j = i * i; j <= n; j += i) {
        result[j] = false;
      }
    }
    return result;
  }

  private static long gcd(long a, long b) {
    return a % b == 0 ? b : gcd(b, a % b);
  }

  private static long lcm(long a, long b) {
    return a * b / gcd(a, b);
  }

  private static long power(long a, long b) {
    long result = 1;
    while (b > 0) {
      if ((b & 1) == 1) {
        result = (result * a) % MOD;
      }
      b >>= 1;
      a = (a * a) % MOD;
    }
    return result;
  }

  private static long modInverse(long a) {
    return power(a, MOD - 2);
  }

  private static long nCr(int n, int r) {
    if (n < r)
      return 0;
    if (r == 0)
      return 1;
    long[] dp = factorial(n);
    return ((dp[n] * modInverse(dp[r]) % MOD) * (modInverse(dp[n - r]) % MOD)) % MOD;
  }

  private static long nCr(int n, int r, long[] dp) {
    if (n < r)
      return 0;
    if (r == 0)
      return 1;
    return ((dp[n] * modInverse(dp[r]) % MOD) * (modInverse(dp[n - r]) % MOD)) % MOD;
  }

  private static long nPr(int n, int r) {
    if (n < r)
      return 0;
    if (r == 0)
      return 1;
    long[] dp = factorial(n);
    return (dp[n] * modInverse(dp[n - r])) % MOD;
  }

  private static long nPr(int n, int r, long[] dp) {
    if (n < r)
      return 0;
    if (r == 0)
      return 1;
    return (dp[n] * modInverse(dp[n - r])) % MOD;
  }

  private static long[] factorial(int n) {
    long[] factorial = new long[n + 1];
    factorial[0] = 1;
    for (int i = 1; i <= n; i++) {
      factorial[i] = (factorial[i - 1] * i) % MOD;
    }
    return factorial;
  }

  private static void printArray(int[] a) {
    for (int i : a) out.print(i + " ");
    out.println();
  }

  private static void printlnArray(int[] a) {
    for (int i : a) out.println(i);
  }

  private static void printMatrix(int[][] a) {
    for (int[] i : a) printArray(i);
  }

  private static void sortArray(int[] a, int order) {
    ArrayList<Integer> l = new ArrayList<>();
    for (int i : a) l.add(i);
    if (order == -1)
      Collections.sort(l, Collections.reverseOrder());
    else
      Collections.sort(l);
    for (int i = 0; i < a.length; i++) a[i] = l.get(i);
  }

  private static class QuickReader {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    StringTokenizer st = new StringTokenizer("");

    String nextLine() {
      String str = "";
      try {
        str = br.readLine();
      } catch (IOException e) {
        e.printStackTrace();
      }
      return str;
    }

    String next() {
      while (!st.hasMoreTokens()) try {
          st = new StringTokenizer(br.readLine());
        } catch (IOException e) {
          e.printStackTrace();
        }
      return st.nextToken();
    }

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

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

    int[] readIntArray(int n) {
      int[] a = new int[n];
      for (int i = 0; i < n; i++) a[i] = nextInt();
      return a;
    }

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

**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 code, we need to consider edge cases that can highlight issues in the logic. The code seems to use a binary search approach to find the maximum possible value at the root, and it relies on a helper function to check the feasibility of a given value. The key areas to focus on are:

1. **Tree Structure**: The structure of the tree can significantly affect the operations and the feasibility checks.
2. **Initial Values**: The initial values of the vertices can influence the operations and the final result.
3. **Operations on the Root**: The operations on the root itself and its immediate children can be critical.

### Step-by-Step Analysis

1. **Tree with a Single Child**:
   - If the root has only one child, the operations will primarily affect this child and the root.
   - This can help expose issues in the logic for handling single-child nodes.

2. **Tree with Multiple Children**:
   - If the root has multiple children, the operations will affect multiple subtrees.
   - This can help expose issues in the logic for handling multiple children and their subtrees.

3. **Initial Values**:
   - If the initial values are such that the root's value is already high, the operations might not be necessary.
   - If the initial values are such that the root's value is very low, the operations might need to be performed multiple times.

### Test Input

Let's create a small-scale test input that focuses on the root having multiple children with low initial values, which can expose issues in the logic for handling multiple children and their subtrees.

```plaintext
1
5
0 0 0 0 0
1 1 1 1
```

### Explanation

- **Test Case Count**: 1
- **Number of Vertices**: 5
- **Initial Values**: [0, 0, 0, 0, 0]
- **Parent Array**: [1, 1, 1, 1] (indicating that vertices 2, 3, 4, and 5 are all children of vertex 1)

### Why This Test Input?

- **Root with Multiple Children**: The root (vertex 1) has four children (vertices 2, 3, 4, and 5).
- **Low Initial Values**: All vertices have an initial value of 0, which means the operations will need to be performed to increase the root's value.
- **Feasibility Check**: The helper function will need to check if it's possible to increase the root's value by performing operations on the children and their subtrees.

This test input should help expose any issues in the logic for handling multiple children and the feasibility checks in the helper function.


**Task:**
Generate a challenging test input that exposes the bug in the buggy code of the algorithm problem:
Algorithm Problem:
Title: Maximize the Root
time_limit_ms: 3000
memory_limit_mb: 256
Description: You are given a rooted tree, consisting of $n$ vertices. The vertices in the tree are numbered from $1$ to $n$, and the root is the vertex $1$. The value $a_i$ is written at the $i$-th vertex.

You can perform the following operation any number of times (possibly zero): choose a vertex $v$ which has at least one child; increase $a_v$ by $1$; and decrease $a_u$ by $1$ for all vertices $u$ that are in the subtree of $v$ (except $v$ itself). However, after each operation, the values on all vertices should be non-negative.

Your task is to calculate the maximum possible value written at the root using the aforementioned operation.

Input: The first line contains a single integer $t$ ($1 \le t \le 10^4$) — the number of test cases.

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

The second line contains $n$ integers $a_1, a_2, \dots, a_n$ ($0 \le a_i \le 10^9$) — the initial values written at vertices.

The third line contains $n-1$ integers $p_2, p_3, \dots, p_n$ ($1 \le p_i \le n$), where $p_i$ is the parent of the $i$-th vertex in the tree. Vertex $1$ is the root.

Additional constraint on the input: the sum of $n$ over all test cases doesn't exceed $2 \cdot 10^5$.

Output: For each test case, print a single integer — the maximum possible value written at the root using the aforementioned operation.

Examples:
input:
3
4
0 1 0 2
1 1 3
2
3 0
1
5
2 5 3 9 6
3 1 5 2
output:
1
3
6

Note: In the first test case, the following sequence of operations is possible:

  * perform the operation on $v=3$, then the values on the vertices will be $[0, 1, 1, 1]$;    * perform the operation on $v=1$, then the values on the vertices will be $[1, 0, 0, 0]$.

Buggy Code:
// package com.atguigu;

import java.io.*;
import java.util.*;

public class Main {

    static PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));

    static class Read{
        StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        public int nextInt() throws Exception{
            st.nextToken();
            return (int) st.nval;
        }
        public long nextLong() throws Exception{
            st.nextToken();
            return (long) st.nval;
        }

    }
    static List<List<Integer>> tree; // 邻接表表示树结构
    static int[] a; // 节点初始值数组
    static long[] need; // 需要传递的操作值
    static int n;

    public static void main(String[] args) throws Exception{
        Read sc = new Read();
        int t = sc.nextInt(); // 测试用例数量

        while (t-- > 0) {
            n = sc.nextInt();
            a = new int[n + 1];
            need = new long[n + 1];
            tree = new ArrayList<>();

            for (int i = 0; i <= n; i++) {
                tree.add(new ArrayList<>());
            }

            // 读取节点值
            for (int i = 1; i <= n; i++) {
                a[i] = sc.nextInt();
            }

            // 构建树，读取父节点信息
            for (int i = 2; i <= n; i++) {
                int parent = sc.nextInt();
                tree.get(parent).add(i);
            }

            // 二分答案
            long low = a[1], high = 2000000000L;
            high = 10;
            long result = a[1];

            while (low <= high) {
                long mid = (low + high) / 2;
                if (dfs(1, mid,0)) {
                    result = mid;
                    low = mid + 1;
                } else {
                    high = mid - 1;
                }
            }

            // 输出结果
            pw.println(result);
        }
        pw.flush();
    }

    public static boolean dfs(int u, long mid,long topVal) {
        if(u == 1){
            if(a[1] >= mid) return true;
            else {
                topVal = mid - a[1];
            }
        }
        boolean flag = true;
        for(int i = 0;i < tree.get(u).size();i++){
            int v = tree.get(u).get(i);
            if(a[v] >= topVal) flag &= dfs(v, mid,topVal);
            else {
                flag &= dfs(v, mid,topVal + topVal - a[v]);
            }
        }
        if(tree.get(u).size() == 0) return a[u] >= topVal;
        return flag;
    }

}

**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, let's consider the following aspects:

1. **Tree Structure**: The tree should be constructed in a way that maximizes the complexity of the operations. This can be achieved by creating a tree with a deep and wide structure, ensuring that the root has multiple children, and those children have their own children, and so on.

2. **Initial Values**: The initial values at the vertices should be chosen to challenge the logic in the `dfs` function. Specifically, we want to ensure that the values are such that the binary search in the `main` function might fail to find the correct maximum value for the root.

3. **Edge Cases**: We should include edge cases where the values at the nodes are very close to the threshold that the `dfs` function is trying to check. This can help in identifying issues with the logic that handles the transfer of values.

Given these considerations, here is a small-scale test input that should expose the bug:

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

### Explanation:
- **Number of Test Cases**: 1
- **Number of Vertices**: 5
- **Initial Values**: [1, 2, 3, 4, 5]
- **Parent Array**: [1, 1, 3, 3] (indicating the parent of each vertex except the root)

### Tree Structure:
- Vertex 1 (root) has children 2 and 3.
- Vertex 3 has children 4 and 5.

### Initial Values:
- Vertex 1: 1
- Vertex 2: 2
- Vertex 3: 3
- Vertex 4: 4
- Vertex 5: 5

### Expected Behavior:
- The root (vertex 1) should be able to gather values from its children and their subtrees. The maximum possible value at the root should be calculated correctly by the algorithm.

### Why This Input is Challenging:
- The root has two children, and one of those children (vertex 3) has two children as well. This structure ensures that the `dfs` function has to handle multiple levels of recursion.
- The initial values are chosen such that the root can potentially gather a significant amount of value from its children, but the binary search in the `main` function might not correctly handle the transfer of values, especially if the `dfs` function has logical flaws.

This test input should help in identifying issues with the binary search and the `dfs` function in the provided buggy code.