【最大子矩陣和】poj 1050 To the Max

http://poj.org/problem?id=1050

最大連續子序列的二維版本,枚舉第i、j行,之間的元素和構成一個n個元素的序列,求其最大連續子序列即可,維護maxx,複雜度O(n^3)

/*
   poj 1050 最大子矩陣和dp
   (一維)最大連續子序列和的拓展(二維)
思路:
   暴力枚舉所有子矩陣求和找最大值,O(n^4)超時
   將二維降成一維,枚舉第i,j行,i-j行每列的元素和作爲一個元素,求其構成的最大連續子序列和
   整個過程中維護一個maxx即可

   拿前綴和預處理了下,複雜度O(n^3)10^6 16ms飄過
*/
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<vector>
#include<queue>
#include<set>
#include<map>
#include<algorithm>
#include<sstream>
#define eps 1e-9
#define pi acos(-1)
#define INF 0x7fffffff
#define inf -INF
#define MM 12900
#define N 50
using namespace std;
typedef long long ll;
const int _max = 100 + 10;

int a[_max][_max],n,col[_max][_max],b[_max];
int dp[_max];

int work(){//最大連續子序列和O(n)
  dp[1] = b[1];//dp[i]以i爲結尾的最大連續子序列和
  int maxx = dp[1];
  for(int i = 2; i <= n; ++ i) {
    if(dp[i-1]+b[i]<b[i]) dp[i] = b[i];
    else dp[i] = dp[i-1] + b[i];
    if(maxx < dp[i]) maxx = dp[i];
  }
  return maxx;
}

int main(){
    #ifndef ONLINE_JUDGE
    freopen("input.txt","r",stdin);
    #endif // ONLINE_JUDGE
    while(scanf("%d",&n)==1){
        for(int i = 1; i <= n; ++ i)
            for(int j = 1; j <= n; ++ j)
            scanf("%d",&a[i][j]);
        //前綴和預處理
        memset(col,0,sizeof(col));
        for(int i = 1; i <= n;++ i) col[i][1] = a[1][i];
        for(int i = 1; i <= n; ++ i)//列
            for(int j = 2; j <= n; ++ j)
            col[i][j] = col[i][j-1] + a[j][i];
        //O(n^3)
        int t,maxx = inf;//會枚舉到所有子矩陣,inf即可,不用a[1][1]
        for(int i = 1;i <= n; ++ i){//枚舉i-j行
            for(int j = i; j <= n; ++ j){
                b[1] = col[1][j]-col[1][i-1];
                for(int k = 2; k <= n; ++ k)
                   b[k] = col[k][j] - col[k][i-1];
                t = work();
                if(maxx<t) maxx = t;
            }
        }
        printf("%d\n",maxx);
    }
    return 0;
}


發佈了201 篇原創文章 · 獲贊 45 · 訪問量 25萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章