标签:
3 4 3 1 2 8 5 3 4 6 1 0 2 3
24
找当前子问题最优解。
#include <cstdio> #include <cstring> #define max(a,b) (a>b?a:b) const int N = 21; int dp[N][N], num[N][N]; int main(){ int n, m; while(scanf("%d%d", &n, &m) != EOF){ memset(dp, 0, sizeof(dp)); for(int i = 1; i <= n; i++) for(int j = 1; j <= m; j++) scanf("%d", &num[i][j]); for(int i = 1; i <= n; i++) for(int j = 1; j <= m; j++) dp[i][j]=max(dp[i-1][j], dp[i][j-1])+num[i][j]; printf("%d\n", dp[n][m]); } return 0; }
2、
最大连续子串和
dp[n]表示当前1->n最大子串和 然后再找最大值就行了, 也算dp思想吧。
得到状态转移方程:
dp[i]=dp[i-1]>0? dp[i]+dp[i-1]+num[i]:dp[i]+num[i];
#include <cstdio> #include <cstring> const int N = 21; int num[N], dp[N]; #define max(a, b) (a>b?a:b) int main(){ int n; while(scanf("%d", &n) != EOF){ memset(dp, 0, sizeof(dp)); for(int i = 1; i <= n; i++) scanf("%d", &num[i]); int maxsum = -1; for(int i = 1; i <= n; i++){ dp[i]=dp[i-1]>0?dp[i]+dp[i-1]+num[i]:dp[i]+num[i]; maxsum=max(maxsum, dp[i]); } printf("%d\n", maxsum); } return 0; }
标签:
原文地址:http://www.cnblogs.com/fengshun/p/5081877.html