This page is still under construction.

Parts of this page are still being built. What you see may change.

Cookie Game

Time limit8sMemory limit1024 MB

Summary
Given a tree where each vertex has 1 or 2 cookies, find the maximum number of cookies a piece can eat when it starts anywhere and moves along edges.
Level

Medium6 of 10

Topics
Tree, Dynamic programming, DFS
Solved
No attempts yet

Problem

There is an undirected tree with NN vertices, numbered 1 through NN. Each vertex has either one or two cookies on it.

You play a game on this tree. First, you choose one vertex and place a piece on it. Then you repeat the following action until the game ends.

  • Eat exactly one cookie on the vertex where the piece currently is. Then choose a vertex adjacent to the current one and move the piece there. If the destination has no cookies left, the game ends at that moment.

If you play optimally, what is the maximum number of cookies you can eat during the game?

Input

The input contains at most 50 datasets. Each dataset has the following format.

N
x1x2...xN
p1
p2
…
pN-1

The first line gives the number of vertices NN (2≤N≤1052 \le N \le 10^5). The second line is a string of NN characters, each 1 or 2. The ii-th character xix_i is the number of cookies initially on vertex ii. The next N−1N-1 lines give the adjacency information. The integer pjp_j on line jj (1≤pj≤j1 \le p_j \le j) means that vertex j+1j+1 is adjacent to vertex pjp_j.

The input ends with a line containing a single zero.

Output

For each dataset, print on one line the maximum number of cookies you can eat during the game.

Examples1

  1. Example 1

    Input
    2
    11
    1
    5
    12121
    1
    2
    3
    4
    8
    12112211
    1
    2
    1
    3
    2
    5
    6
    5
    12122
    1
    2
    3
    4
    0
    
    Expected output
    2
    7
    11
    8