The new ITone 6 has been released recently and George got really keen to buy it. Unfortunately, he didn't have enough money, so George was going to work as a programmer. Now he faced the following problem at the work.
Given a sequence of n integers p1, p2, ..., pn. You are to choose k pairs of integers:
in such a way that the value of sum
is maximal possible. Help George to cope with the task.
The first line contains three integers n, m and k (1 ≤ (m × k) ≤ n ≤ 5000). The second line contains n integers p1, p2, ..., pn(0 ≤ pi ≤ 109).
Print an integer in a single line — the maximum possible value of sum.
5 2 1
1 2 3 4 5
9
7 1 3
2 10 7 18 5 33 0
61
题意:从一个长度为n的数列中选出k段区间长度为m的段,使得这k段数的和最大。
思路:DP方程:dp[i][j] = max(dp[i - 1][j], dp[i - m][j - 1] + sum[i] - sum[i - m]);
dp[i][j]表示前i个数中选j段的最大和,sum[i]表示前i个数的和。
1 #include<algorithm> 2 #include<iostream> 3 #include<limits.h> 4 #include<stdlib.h> 5 #include<string.h> 6 #include<complex> 7 #include<cstring> 8 #include<iomanip> 9 #include<stdio.h> 10 #include<bitset> 11 #include<cctype> 12 #include<math.h> 13 #include<string> 14 #include<time.h> 15 #include<vector> 16 #include<cmath> 17 #include<queue> 18 #include<stack> 19 #include<list> 20 #include<map> 21 #include<set> 22 23 #define LL long long 24 25 using namespace std; 26 const LL mod = 1e9 + 7; 27 const double PI = acos(-1.0); 28 const double E = exp(1.0); 29 const int M = 5005; 30 31 int a[M]; 32 LL ans[M]; 33 LL dp[M][M]; 34 35 int main() 36 { 37 int n, m, k; 38 cin >> n >> m >> k; 39 for(int i = 1; i <= n; ++i){ 40 cin >> a[i]; 41 ans[i] = ans[i - 1] + a[i]; 42 } 43 for(int i = m; i <= n; ++i) 44 for(int j = 1; j <= k; ++j) 45 dp[i][j] = max(dp[i - 1][j],dp[i - m][j - 1] + ans[i] - ans[i - m]); 46 cout << dp[n][k] << endl; 47 return 0; 48 }
浙公网安备 33010602011771号