atcoder#ABC261D. [ABC261D] Flipping and Bonus

[ABC261D] Flipping and Bonus

Score : 400400 points

Problem Statement

Takahashi will toss a coin NN times. He also has a counter, which initially shows 00.

Depending on the result of the ii-th coin toss, the following happens:

  • If it heads: Takahashi increases the counter's value by 11 and receives XiX_i yen (Japanese currency).
  • If it tails: he resets the counter's value to 00, without receiving money.

Additionally, there are MM kinds of streak bonuses. The ii-th kind of streak bonus awards YiY_i yen each time the counter shows CiC_i.

Find the maximum amount of money that Takahashi can receive.

Constraints

  • 1MN50001\leq M\leq N\leq 5000
  • 1Xi1091\leq X_i\leq 10^9
  • 1CiN1\leq C_i\leq N
  • 1Yi1091\leq Y_i\leq 10^9
  • C1,C2,,CMC_1,C_2,\ldots,C_M are all different.
  • All values in input are integers.

Input

Input is given from Standard Input in the following format:

NN MM

X1X_1 X2X_2 \ldots XNX_N

C1C_1 Y1Y_1

C2C_2 Y2Y_2

\vdots

CMC_M YMY_M

Output

Print the maximum amount of money that Takahashi can receive, as an integer.

6 3
2 7 1 8 2 8
2 10
3 1
5 5
48

If he gets head, head, tail, head, head, head, in this order, the following amounts of money are awarded.

  • In the 11-st coin toss, the coin heads. Change the counter's value from 00 to 11 and receive 22 yen.
  • In the 22-nd coin toss, the coin heads. Change the counter's value from 11 to 22 and receive 77 yen. Additionally, get 1010 yen as a streak bonus.
  • In the 33-rd coin toss, the coin tails. Change the counter's value from 22 to 00.
  • In the 44-th coin toss, the coin heads. Change the counter's value from 00 to 11 and receive 88 yen.
  • In the 55-th coin toss, the coin heads. Change the counter's value from 11 to 22 and receive 22 yen. Additionally, get 1010 yen as a streak bonus.
  • In the 66-th coin toss, the coin heads. Change the counter's value from 22 to 33 and receive 88 yen. Additionally, get 11 yen as a streak bonus.

In this case, Takahashi receives 2+(7+10)+0+8+(2+10)+(8+1)=482+(7+10)+0+8+(2+10)+(8+1)=48 yen in total, which is the maximum possible. Note that streak bonuses are awarded any number of times each time the counter shows CiC_i. As a side note, if he gets head in all 66 coin tosses, he only receives 2+(7+10)+(1+1)+8+(2+5)+8=442+(7+10)+(1+1)+8+(2+5)+8=44 yen, which is not the maximum.

3 2
1000000000 1000000000 1000000000
1 1000000000
3 1000000000
5000000000

Note that the answer may not fit into a 3232-bit integer type.