计蒜客练习题:最大子阵(C语言)动态规划

在这里插入图片描述

#include<stdio.h>
#include<stdlib.h>
#define MAX 100
int a[MAX][MAX];
int max=-99999;
int main()
{
    int i,j,m,n;
    int *b,dp[MAX],str=1;
    scanf("%d%d",&n,&m);
    for(i=1;i<=n;i++)
    {
       for(j=1;j<=m;j++)
       {
         scanf("%d",&a[i][j]);
        }
    }
    
    for(str = 1;str<=n;str++)
    {
        b=(int *)calloc(m,sizeof(int));
        for(i=str;i<=n;i++)
        {
           for(j=1;j<=m;j++)
           {
               b[j]+=a[i][j];
           }
          dp[1]=b[1];
            if(dp[1]>max)
            {
              max=dp[1];
            }
            for(j=2;j<= m ;j++)
            {
                if(dp[j-1]<0)
                {
                   dp[j]=b[j];
                }else
                {
                   dp[j]=dp[j-1]+b[j];
                }
                if(dp[j]>max)
                {
     max=dp[j];
                }
            }
        }
     }
    printf("%d",max);
    return 0;
}

代码分析:
b代表按列取子矩阵,dp在按行列求的同时找出最大值

猜你喜欢

转载自blog.csdn.net/qq_42580577/article/details/86571736