PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#DSU0000069. Phá hủy dãy số (Destroying Array)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Phá hủy dãy số (Destroying Array)

Destroying Array

Source: Codeforces

Version: Phuoc Hung OJ Extended

Problem Statement

Given an array of nn non-negative integers a1,…,ana_1,\ldots,a_n, positions will be destroyed in the order of a permutation p1,…,pnp_1,\ldots,p_n.

After each destruction, consider every contiguous segment of the original array that contains no destroyed position. Find the greatest sum of such a segment. An empty segment has sum 00, so the final answer after all positions are destroyed is 00.

Removing an element does not make its neighbors on either side adjacent. For example, after position 33 is removed, positions 22 and 44 cannot belong to the same valid segment even if both remain present.

After each removal, consider all contiguous segments containing no removed positions and select the largest sum. If no nonempty segment remains, the answer is 00. All array values are nonnegative, so the answer cannot be negative.

Input

The first line contains nn, the second contains a1,…,ana_1,\ldots,a_n, and the third contains the destruction permutation p1,…,pnp_1,\ldots,p_n.

Output

Print nn lines; line ii is the largest valid segment sum after positions p1,…,pip_1,\ldots,p_i are destroyed.

Subtasks

  • Subtask 1 (20 points): 1≤n≤301\le n\le 30; 0≤ai≤1090\le a_i\le10^9; p1,…,pnp_1,\ldots,p_n is a permutation of 1,…,n1,\ldots,n.
  • Subtask 2 (30 points): 1≤n≤40001\le n\le 4000; 0≤ai≤1090\le a_i\le10^9; p1,…,pnp_1,\ldots,p_n is a permutation of 1,…,n1,\ldots,n.
  • Subtask 3 (50 points): 1≤n≤1000001\le n\le 100000; 0≤ai≤1090\le a_i\le10^9; p1,…,pnp_1,\ldots,p_n is a permutation of 1,…,n1,\ldots,n.

Examples

Input

4
1 3 2 5
3 4 1 2

Output

5
4
3
0

Explanation

After removing position 33, the maximum remaining segment sum is 55. Removing position 44 next leaves a best segment of sum 1+3=41+3=4. After removing position 11, the best sum is 33. Once all positions have been removed, the answer is 00.