此题的思想是dp,是最大连续子段和的变形题目。
由一维变成了二维,思想还是一样的,和两行相加变成一行,同理。
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define MAXN 101
#define INF 0x3f3f3f3f
int v[MAXN][MAXN], dp[MAXN], ans;
int select_max(const int &n)
{
int sum(0), tmp(0);
for(int i = 0; i < n; i ++) {
if( tmp+dp[i] < 0 ) {
tmp = 0; continue;
}
sum = max(sum, tmp += dp[i]);
}
return sum;
}
int dynamic_programming(const int &n)
{
ans = -INF;
for(int i = 0; i < n; i ++) {
for(int j = 0; j < n; j ++) {
dp[j] = v[i][j];
}
for(int j = i+1; j < n; j ++) {
for(int k = 0; k < n; k ++) {
dp[k] += v[j][k];
}
ans = max(ans, select_max(n));
}
}
return ans;
}
int main(int argc, char const *argv[])
{
#ifndef ONLINE_JUDGE
freopen("test.in","r", stdin);
#endif
int n;
while( ~scanf("%d", &n) ) {
for(int i = 0; i < n; i ++) {
for(int j = 0; j < n; j ++) {
scanf("%d", &v[i][j]);
}
}
printf("%d\n", dynamic_programming(n));
}
return 0;
}
09-04
09-04
09-04
09-04