【最大子矩阵和】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万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章