Under construction

Still being built. Things may change

Balloon Darts

Interview

Time limit1sMemory limit512 MB

Summary
Given balloon scores and a burst order, find the highest segment score recorded at any point while the balloons are burst.
Level

Medium5 of 10

Topics
Union-find, Implementation
Solved
No attempts yet

Problem

A lonely coder named Byeongwoo was set up on a date by his friends, and the two went to an amusement park.

While chatting on a bench, Byeongwoo noticed a balloon dart game across the way. He wanted a high score to win a teddy bear, so he walked over to play. The park's game followed rules unlike any ordinary balloon dart game he knew.

  1. The balloons are arranged in a single line, like a one-dimensional array.

  2. There are as many darts as balloons. Byeongwoo is a dart master, so every dart he throws hits its balloon exactly and bursts it.

  3. The score is the sum, over every segment, of (the sum of the balloon scores in the segment) times (the size of the segment). A segment is a contiguous subarray. More precisely, for an interval [l,r][l, r] where all balloons in [l,r][l, r] are still present, and balloon l−1l-1 and balloon r+1r+1 either do not exist or have been burst, the segment is the subarray al,al+1,⋯ ,ara_l, a_{l+1}, \cdots, a_r of the full array aa. The score is given by the formula below.

∑i=1k(segi×size(segi))\sum\limits_{i=1}^{k} (seg_i \times size(seg_i))

  • segiseg_i is the sum of the balloon scores in the ii-th segment.
  • size(segi)size(seg_i) is the size of the interval of the ii-th segment.
  • kk is the total number of segments.
  1. The score starts at 0 and is recalculated each time a dart bursts a balloon. The final score is the highest score recorded. Before the first dart is thrown, no score has been calculated, so the score is 0.

Input

The first line contains the number of balloons, an integer NN (3≤N≤100 0003 \le N \le 100\,000).

The second line contains NN integers B1,B2,⋯ ,BNB_1, B_2, \cdots, B_N (−100 000≤Bi≤100 000-100\,000 \le B_i \le 100\,000), the scores of the balloons.

The third line contains NN distinct integers P1,P2,⋯ ,PNP_1, P_2, \cdots, P_N (1≤Pi≤N1 \le P_i \le N), the order in which the balloons are burst.

Output

Print the final score.

Examples3

  1. Example 1

    Input
    5
    13 7 8 -20 21
    2 4 1 3 5
    
    Expected output
    42
    
  2. Example 2

    Input
    3
    -40 -9 -19
    3 1 2
    
    Expected output
    0
    
  3. Example 3

    Input
    11
    6 28 15 17 23 39 -22 -30 -17 -24 28
    10 11 5 2 4 6 3 7 9 1 8
    
    Expected output
    559