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

#FT0000055. Chia dãy thành các đoạn với chi phí nhỏ nhất II (Divide an Array Into Subarrays With Minimum Cost II)

HỌC THEO LỘ TRÌNH

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

1 lộ trình

Chia dãy thành các đoạn với chi phí nhỏ nhất II (Divide an Array Into Subarrays With Minimum Cost II)

Divide an Array Into Subarrays With Minimum Cost II

Source: LeetCode

Version: Phuoc Hung OJ Extended

Problem Statement

Partition the array aa of length nn into exactly kk nonempty, disjoint, consecutive subarrays that cover the entire array in order. The cost of a subarray equals its first element; the total cost is the sum of all kk first elements.

Let s2s_2 and sks_k denote the zero-based starting positions of the second and kk-th subarrays. The partition is valid only when sk−s2≤dists_k-s_2\le dist. Find the minimum total cost over all valid partitions.

Input

  • Line 1: integers n,k,distn,k,dist for array length, number of partitions and maximum difference between the specified starts.
  • Line 2: exactly nn integers a0,…,an−1a_0,\ldots,a_{n-1}.

Output

Print exactly one integer: the minimum total cost of a valid partition.

Subtasks

Subtask 1 (20 points):

  • 3≤n≤203\le n\le 20; 3≤k≤n3\le k\le n; k−2≤dist≤n−2k-2\le dist\le n-2; 1≤ai≤1091\le a_i\le10^9 for every 0≤i<n0\le i<n.

Subtask 2 (30 points):

  • 3≤n≤20003\le n\le 2000; 3≤k≤n3\le k\le n; k−2≤dist≤n−2k-2\le dist\le n-2; 1≤ai≤1091\le a_i\le10^9 for every 0≤i<n0\le i<n.

Subtask 3 (50 points):

  • 3≤n≤1000003\le n\le 100000; 3≤k≤n3\le k\le n; k−2≤dist≤n−2k-2\le dist\le n-2; 1≤ai≤1091\le a_i\le10^9 for every 0≤i<n0\le i<n.

Examples

Examples 1

Input

6 3 3
1 3 2 6 4 2

Output

5

Explanation

Choose [1,3][1,3], [2,6,4][2,6,4], and [2][2]. Their starts are 0,2,50,2,5 and 5−2=3=dist5-2=3=dist. Their costs are 1,2,21,2,2, yielding total 5, which is minimal for the given sequence.

Examples 2

Input

4 3 1
10 8 18 9

Output

36

Explanation

The last two subarrays must start at adjacent positions because dist=1dist=1. Starting at indices 1 and 2 costs 10+8+18=3610+8+18=36, whereas starting at 2 and 3 costs 10+18+9=3710+18+9=37. Thus the answer is 36.