POJ 2593

Max Sequence:求两个子序列的最大和,此题与POJ 2479算法完全一致,均采用动态规划求解。

测试数据:
10
1 -1 2 2 3 -3 4 -4 5 -5
5
-5 9 -5 11 20
6
3 3 -3 4 -2 1
0
正确的运行结果是:
13
40
10

代码如下#include <iostream> using namespace std; #define CASE_NUM 40 #define LENGTH 100000 int x[LENGTH]; int a[LENGTH];//存每个段最大值 int b[LENGTH]; int GetMaxSubSum(int n) { int i,j; a[0] = x[0]; int sum = x[0]; for (i = 1; i < n-1; i++) { if (x[i]<=0 && x[i]<=a[i-1])//仅这种情况下,丢弃当前的x[i]值 a[i] = a[i-1]; else { if (sum < 0) sum = 0; a[i] = sum + x[i]; } sum += x[i]; }//for b[n-2] = x[n-1]; sum = x[n-1]; for (i = n-3; i >= 0; i--) { if (x[i+1]<=0 && x[i+1]<=b[i+1]) b[i] = b[i+1]; else { if (sum <= 0) sum = 0; b[i] = sum + x[i+1]; } sum += x[i+1]; } int max = a[0] + b[0]; for (j = 0; j < n-1; j++) { int tmp = a[j] + b[j]; if (max < tmp) max = tmp; } return max; } int main(int argc, char* argv[]) { int nCase; int ans[CASE_NUM]; int i,j; for (i = 0; ; i++) { int n; cin >> n; if (n == 0) break; for (j = 0; j < n; j++) cin >> x[j]; ans[i] = GetMaxSubSum(n); } nCase = i; for (j = 0; j < nCase; j++) cout << ans[j] << endl; return 0; }

你可能感兴趣的:(POJ 2593)