poj 2479 Maximum sum(DP)
题意:求两段连续和使之最大
思路:两个方向都处理。先正方向求出到每个index的连续最大和,然后从前往后把每个位置的最大和都更新一下(更新为前边所有和中最大的那个),反方向做同样的处理。
然后i 1..n枚举
1 #include<iostream> 2 #include<cstdio> 3 #include<cstdlib> 4 #include<cstring> 5 #include<string> 6 #include<queue> 7 #include<algorithm> 8 #include<map> 9 #include<iomanip> 10 #include<climits> 11 #include<string.h> 12 #include<numeric> 13 #include<cmath> 14 #include<stdlib.h> 15 #include<vector> 16 #include<stack> 17 #include<set> 18 #define INF 1e7 19 #define MAXN 100010 20 #define maxn 1000010 21 #define Mod 1000007 22 #define N 1299800 23 using namespace std; 24 typedef long long LL; 25 26 int T; 27 int n, num[50010]; 28 int sum1[50010],sum2[50010]; 29 30 void run() 31 { 32 scanf("%d", &n); 33 memset(sum1, 0, sizeof(sum1)); 34 memset(sum2, 0, sizeof(sum2)); 35 memset(num, 0, sizeof(num)); 36 for (int i = 1; i <= n; ++i) 37 scanf("%d",&num[i]); 38 if (n == 2) { 39 printf("%d\n",num[1] + num[2]); 40 return; 41 } 42 for (int i = 1; i <= n; ++i) { 43 if (sum1[i - 1] > 0) 44 sum1[i] = sum1[i - 1] + num[i]; 45 else sum1[i] = num[i]; 46 } 47 for (int i = 1; i <= n; ++i) 48 sum1[i] = max(sum1[i - 1], sum1[i]); 49 for (int i = n; i >= 1; --i) { 50 if (sum2[i + 1] > 0) 51 sum2[i] = sum2[i + 1] + num[i]; 52 else sum2[i] = num[i]; 53 } 54 for (int i = n; i >= 1; --i) 55 sum2[i] = max(sum2[i],sum2[i+1]); 56 int ans = -INF; 57 for (int i = 1; i <= n; ++i) 58 ans = max(ans, sum1[i] + sum2[i + 1]); 59 printf("%d\n",ans); 60 } 61 62 int main() 63 { 64 scanf("%d", &T); 65 while (T--) 66 run(); 67 return 0; 68 }