#K50897. Collect Apples

    ID: 28966 Type: Default 1000ms 256MiB

Collect Apples

Collect Apples

You are given a rooted directed graph of n nodes, where each node contains a certain number of apples. Each node has at most one outgoing edge which indicates the next node to visit. If a node has an outgoing edge value of 0, then it does not point to any other node. Starting from each node, you must simulate the process of collecting apples by following the directed edge chain until you reach a node with no outgoing edge. The goal is to compute the total number of apples collected when starting from each node.

The collection process is defined as follows:

  • Begin at a starting node and add its apple count.
  • If the node has an outgoing edge, move to the designated next node and repeat the process.
  • If the node does not have an outgoing edge, stop.

Your task is to output an array of n integers where the i-th value represents the maximum apples collected when starting from node i.

The relation can be expressed in LaTeX as:

\( \text{result}[i] = apple\_values[i] + \begin{cases} 0, & \text{if } edges[i] = 0 \\ \text{result}[edges[i]-1], & \text{otherwise} \end{cases} \)

inputFormat

The input will be read from standard input (stdin) and has the following format:

  • The first line contains an integer \( n \) indicating the number of nodes.
  • The second line contains \( n \) space-separated integers representing the apple values at each node.
  • The third line contains \( n \) space-separated integers representing the directed edge from each node. A value of 0 means that the node has no outgoing edge; otherwise, the value is the 1-indexed target node.

outputFormat

Output a single line to standard output (stdout) containing \( n \) space-separated integers. The \( i\text{-th} \) integer represents the total number of apples collected when starting from node \( i \).

## sample
4
4 2 3 1
2 3 4 0
10 6 4 1