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

#BS0000459. Chặn phần tử (Blocking Elements)

    ID: 3584 Loại: Thông thường 4000ms 256MiB Tried: 0 Đã chấp nhận: 0 Độ khó: 1 Đăng bởi: Nhãn>Binary search on answerPrefix sumsDynamic programming basicsMonotonic queueOptimization with monotonic queues
HỌC THEO LỘ TRÌNH

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

1 lộ trình

Chặn phần tử (Blocking Elements)

Blocking Elements

Source: Codeforces

Version: Phuoc Hung OJ Extended

Problem Statement

You have an array of positive integers a1,a2,…,ana_1,a_2,\ldots,a_n. Choose any subset of its positions to block, including the empty subset or the entire array.

Let the selected positions be b1<b2<⋯<bmb_1<b_2<\cdots<b_m. Removing these entries splits the original array into consecutive runs between the blocked positions and the array boundaries. An empty run has sum zero. The cost of the selection is the largest of the following quantities:

  • The combined value of all blocked entries.
  • The sum of each remaining consecutive run.

For instance, blocking positions 22 and 55 in [1,4,5,3,3,2][1,4,5,3,3,2] gives a blocked sum of 77 and run sums of 1,8,21,8,2, so its cost is 88.

Find the smallest possible cost.

Input

The first line contains an integer nn.

The second line contains nn integers a1,a2,…,ana_1,a_2,\ldots,a_n.

Output

Print the minimum cost as an integer.

Subtasks

  • Subtask 1 (20 points): 1≤n≤181\le n\le18; 1≤i≤n1\le i\le n; 1≤ai≤1091\le a_i\le10^9.
  • Subtask 2 (30 points): 1≤n≤20001\le n\le2000; 1≤i≤n1\le i\le n; 1≤ai≤1091\le a_i\le10^9.
  • Subtask 3 (50 points): 1≤n≤1000001\le n\le100000; 1≤i≤n1\le i\le n; 1≤ai≤1091\le a_i\le10^9.

Examples

Input 1

6
1 4 5 3 3 2

Output 1

7

Explanation 1

Block positions 2 and 4, giving blocked sum 7 and run sums 1, 5, 5. Cost 6 is impossible: blocking position 3 leaves insufficient budget to block any entry in the final run [3,3,2], of sum 8. Otherwise both neighbors of position 3 must be blocked, costing at least 7.

Input 2

5
1 2 3 4 5

Output 2

5

Explanation 2

Block positions 1 and 4: the blocked sum and both nonempty run sums are 5. The largest entry is 5, so every selection costs at least 5.

Input 3

6
4 1 6 3 10 7

Output 3

11

Explanation 3

Block positions 2 and 5: blocked sum 11, run sums 4, 9, 7. Cost 10 is impossible: blocking the entry 10 leaves no budget for other entries and the preceding run sums to 14. Keeping the entry 10 requires blocking both neighbors, of values 3 and 7, exhausting the budget while leaving the initial run [4,1,6] of sum 11.