【解题报告】 POJ1050 To the Max

【解题报告】 POJ1050 To the Max

题目:最大的和(已翻译)

题意简述:

就是一个矩阵中找一个和最大的子矩阵

解题思路:

贪心,我们可以首先在输入的时候贪一遍心,然后我们可以一行一行地贪心,最终得到最后的正确结果

AC代码

#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn=105;
int n;
int a[maxn][maxn],s[maxn][maxn];
int ans=-0x3f,nans;
bool check=false;
int max(int a,int b)
{
    return a>b? a:b;
}
int main()
{
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=n;j++)
        {
            cin>>a[i][j];
            if(a[i][j]>=0)
            check=true;
            ans=max(ans,a[i][j]);
        }
    }
    if(!check)
    {
        cout<<ans<<endl;
        return 0;
    }
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=n;j++)
        s[i][j]=s[i-1][j]+a[i][j];
    }
    for(int i=1;i<=n;i++)
    {
        for(int j=i;j<=n;j++)
        {
            nans=0;
            for(int k=1;k<=n;k++)
            {
                nans+=s[j][k]-s[i-1][k];
                if(nans<0)
                nans=0;
                if(nans>ans)
                ans=nans;
            }
        }
    }
    cout<<ans<<endl;
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/wweiyi2004/p/11371048.html
今日推荐