題目連結:http://acm.hdu.edu.cn/showproblem.php?pid=1024
題目大意:n個數分成兩兩不相交的m段,求使這m段和的最大值。
解題思路:比較坑的點:n2 能過;long long逾時,int AC。
dp[i][j]:= 在選擇第i個數的情況下前i個數分成j段的最大值
dp[i][j] = max(dp[i - 1][j] + a[i], max(dp[x][j - 1] -> dp[x][j - 1]) + a[i]) x < i
由于n<1000000,并且更新dp[i][j]時隻用到了j和j-1的部分,是以采用滾動數組記錄選擇第i個人時前i個人分成j段的和最大值;同時,max(dp[x][j - 1] -> dp[x][j - 1]) 可以在更新dp[i]的同時記錄,這樣就将時間複雜度降低到了n2 (是以為什麼n2能過???)
另外就是一些細節問題。
代碼:
1 const int inf = 0x3f3f3f3f;
2 //dp[i][j]:= 在選擇第i個數的情況下前i個數分成j段的最大值
3 //dp[i][j] = max(dp[i - 1][j] + a[i], max(dp[x][j - 1] -> dp[x][j - 1]) + a[i]) x < i
4 const int maxn = 1e6 + 5;
5 int dp[maxn];
6 int pre[maxn];
7 int a[maxn], n, m;
8
9 int solve(){
10 memset(dp, 0, sizeof(dp));
11 memset(pre, 0, sizeof(pre));
12 int tmax = -inf;
13 for(int j = 1; j <= m; j++){
14 tmax = -inf;//記錄前i個人本次的最大值
15 for(int i = j; i <= n; i++){
16 dp[i] = max(dp[i - 1] + a[i], pre[i - 1] + a[i]);//使用的是未更新的值,對應j-1的
17 pre[i - 1] = tmax; //再更新
18 tmax = max(tmax, dp[i]);
19 }
20 }
21 return tmax; //不一定是dp[n],最後一個可能不用選
22 }
23
24 int main(){
25 while(scanf("%d %d", &m, &n) != EOF){
26 for(int i = 1; i <= n; i++) scanf("%d", &a[i]);
27 int ans = solve();
28 printf("%d\n", ans);
29 }
30 }
題目:
Max Sum Plus Plus
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 30900 Accepted Submission(s): 10889
Problem Description Now I think you have got an AC in Ignatius.L's "Max Sum" problem. To be a brave ACMer, we always challenge ourselves to more difficult problems. Now you are faced with a more difficult problem.
Given a consecutive number sequence S 1, S 2, S 3, S 4 ... S x, ... S n (1 ≤ x ≤ n ≤ 1,000,000, -32768 ≤ S x ≤ 32767). We define a function sum(i, j) = S i + ... + S j (1 ≤ i ≤ j ≤ n).
Now given an integer m (m > 0), your task is to find m pairs of i and j which make sum(i 1, j 1) + sum(i 2, j 2) + sum(i 3, j 3) + ... + sum(i m, j m) maximal (i x ≤ i y ≤ j x or i x≤ j y ≤ j x is not allowed).
But I`m lazy, I don't want to write a special-judge module, so you don't have to output m pairs of i and j, just output the maximal summation of sum(i x, j x)(1 ≤ x ≤ m) instead. ^_^
Input Each test case will begin with two integers m and n, followed by n integers S 1, S 2, S 3 ... S n.
Process to the end of file.
Output Output the maximal summation described above in one line.
Sample Input 1 3 1 2 3 2 6 -1 4 -2 3 -2 3
Sample Output 6 8 Hint Huge input, scanf and dynamic programming is recommended.
Author JGShining(極光炫影)