51nod1051_DP求最大子矩陣

題目鏈接:最大子矩陣和
題目描述當所有數都爲負數時輸出0,意味着除了都爲0的情況,總存在一個數>=0,即結果一定>=0,所以當中間結果tmp<0時,後面加它都必然使得結果更小,意味着上面的段不用,tmp置爲0,從下一段重新開始尋找可能的最大值。轉化爲最大子段和求解。

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
#include<stack>
#include<vector>
#include<cmath>
#include<map>
#include<set>
#include<cstdlib>
#define mem(a,b) memset(a,b,sizeof(a))
typedef long long ll;
using namespace std;
const int maxn = 510;
int x,y;
ll dp[maxn][maxn],num;
int main(){
    ll ans;
    while(scanf("%d%d",&x,&y) != EOF){
        mem(dp,0);
        for(int i = 1; i <= y; i++){
            for(int j = 1; j <= x; j++){
                scanf("%lld",&num);
                dp[i][j] = dp[i-1][j] + num;
            }
        }
        ans = 0;
        ll tmp;
        for(int i = 1; i <= y; i++){
            for(int j = i; j <= y; j++){
                tmp = 0;
                for(int k = 1; k <= x; k++){
                    tmp += dp[j][k] - dp[i-1][k];
                    if(tmp < 0) tmp = 0;
                    if(tmp > ans) ans = tmp;
                }
            }
        }
        printf("%lld\n",ans);
    }

    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章