首页 > 代码库 > POJ1050 To the Max

POJ1050 To the Max

题解:

二维最大连续字段和问题。

对列枚举i,j,就变成一维最大连续字段和问题了

最大连续字段和问题:dp[i]表示以i结尾的最大连续字段和 dp[i]=max(dp[i-1]+a[i],a[i]);

代码:

#include<iostream>#include<cstring>#include<cstdio>#include<algorithm>#include<cmath>#include<map>#include<set>#include<vector>using namespace std;using namespace std;#define pb push_back#define mp make_pair#define se second#define fs first#define ll long long#define MS(x,y) memset(x,y,sizeof(x))#define MC(x,y) memcpy(x,y,sizeof(x))#define ls o<<1#define rs o<<1|1#define SZ(x) ((int)(x).size())#define FOR(it,c) for(__typeof((c).begin()) it=(c).begin();it!=(c).end();it++)typedef pair<int,int> P;const double eps=1e-9;const int maxn=50100;const int N=1e9;const int mod=1e9+7;ll read(){    ll x=0,f=1;char ch=getchar();    while(ch<0||ch>9){if(ch==-)f=-1;ch=getchar();}    while(ch>=0&&ch<=9){x=x*10+ch-0;ch=getchar();}    return x*f;}//-----------------------------------------------------------------------------int m[105][105],sum[105][105];int a[105],dp[105];int main(){    int n;    scanf("%d",&n);    for(int i=1;i<=n;i++)    for(int j=1;j<=n;j++){        scanf("%d",&m[i][j]);        sum[i][j]=sum[i][j-1]+m[i][j];    }    int Max=m[1][1];    for(int i=1;i<=n;i++){        for(int j=i;j<=n;j++){            for(int k=1;k<=n;k++) a[k]=sum[k][j]-sum[k][i-1];            dp[1]=a[1];            Max=max(Max,dp[1]);            for(int i=2;i<=n;i++){                dp[i]=max(dp[i-1]+a[i],a[i]);                    Max=max(Max,dp[i]);            }        }    }    printf("%d\n",Max);    return 0;} 

 

POJ1050 To the Max