大意:问你最大的矩阵和,坑死我了WA了n发。。原来做的方法错了。没有考虑当答案为负值的时候
dp[i][j][k]表示i行j列从k个元素开始往前的和,三重循环保证所有情况都遍历到
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int dp[150][150][150];
int a[150][150];
const int inf = 0x3f3f3f3f;
int main()
{
int n;
while(~scanf("%d",&n)){
for(int i = 1; i <= n ; i++)
for(int j = 1; j <= n ;j++)
scanf("%d",&a[i][j]);
memset(dp,0,sizeof(dp));
int ans = -inf;
for(int i = 1; i <= n ; i++){
for(int j = 1; j <= n ;j++){
int sum = 0;
for(int k = j; k >= 1; k--){
sum += a[i][k];
dp[i][j][k] = max(sum + dp[i-1][j][k],sum);
ans = max(ans,dp[i][j][k]);
}
}
}
printf("%d\n",ans);
}
return 0;
}
错误代码也来一发....祭奠我8个WA一个CE..
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int main()
{
int a[150][150];
int n,m;
scanf("%d",&n);
for(int i = 1; i <= n ;i++){
for(int j = 1; j <= n ;j++){
scanf("%d",&m);
a[i][j] = a[i-1][j] + m;
}
}
int max1 = 0;
int sum;
for(int i = 1; i <= n ;i++){
for(int j = i+1 ; j<= n ;j++){
int sum = 0;
for(int k = 1; k <= n;k++){
int temp = a[j][k] - a[i][k];
sum += temp;
if(sum < 0) sum = 0;
if(sum > max1) max1 = sum;
}
}
}
printf("%d",max1);
return 0;
}