HDU 1024 Max Sum Plus Plus【DP+优化时间复杂度】
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 S1, S2, S3, S4 ... Sx, ... Sn (1 ≤ x ≤ n ≤ 1,000,000, -32768 ≤ Sx ≤ 32767). We define a function sum(i, j) = Si + ... + Sj (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(i1, j1) + sum(i2, j2) + sum(i3, j3) + ... + sum(im, jm) maximal (ix ≤ iy ≤ jx or ix ≤ jy ≤ jx 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(ix, jx)(1 ≤ x ≤ m) instead. ^_^
Given a consecutive number sequence S1, S2, S3, S4 ... Sx, ... Sn (1 ≤ x ≤ n ≤ 1,000,000, -32768 ≤ Sx ≤ 32767). We define a function sum(i, j) = Si + ... + Sj (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(i1, j1) + sum(i2, j2) + sum(i3, j3) + ... + sum(im, jm) maximal (ix ≤ iy ≤ jx or ix ≤ jy ≤ jx 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(ix, jx)(1 ≤ x ≤ m) instead. ^_^
Input
Each test case will begin with two integers m and n,
followed by n integers S1, S2,
S3 ... Sn.
Process to the end of file.
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.
思路 |
思路很清晰,但是超时掉,寻找优化算法. 题意:是找K段序列和使他的和最大。 状态转移方程为: f[i][j]表示连续j个数分成i段最大 f[i-1][j-1]+a[i] 当i==j时 f[i][j]= max(f[i-1][k]) i-1=<k<=j-1 但是这样算法的时间复杂度达到O(n^3)会超时,因此再算出来 f[i][j]时就把最大的f[i][k]算出来,时间复杂度为O(n^2) |
源码 |
#include<stdio.h> #include<string.h> #include<iostream> #include<algorithm> using namespace std; #define INF 999999999 int a[1000023]; __int64 f[2][1000023]; int main() { int i, j, n, m, k; while(scanf("%d%d", &m, &n)!=EOF) { //memset(a, 0, sizeof(a)); //memset(f, 0, sizeof(f)); //这里会导致超时 for(i=1; i<=n; i++) { scanf("%d", &a[i]); f[1][i]=f[0][i]=0; } int t=1; for(i=1; i<=m; i++) { f[t][i]=f[1-t][i-1]+a[i]; f[1-t][i]=f[1-t][i-1]>f[1-t][i]?f[1-t][i-1]:f[1-t][i]; for(j=i+1; j<=n; j++) { f[t][j]=(f[t][j-1]>f[1-t][j-1]?f[t][j-1]:f[1-t][j-1])+a[j]; f[1-t][j]=f[1-t][j]>f[1-t][j-1]?f[1-t][j]:f[1-t][j-1]; } t=1-t; } t=1-t; __int64 maxnum=-INF; for(i=m; i<=n; i++) maxnum=max(maxnum, f[t][i]); printf("%d\n", maxnum); } }
|