poj 1050 最大子矩阵和

简介:

一、思路

最大子矩阵和的方法和最大字段和一样

先单独对每行求最大字段和(此时,子矩阵的行为1,就是最大字段和了)

然后,把第i行后的各行对应列的元素加到第i行的对应列元素,每加一行,就求一次最大字段和,这样就把子矩阵的多行压缩为一行了,一行了就是最大字段和了

也可以这样理解:

a11 a12 a13
a21 a22 a23
a31 a32 a33

如图,先求第一行最大子段和,再求第一行跟第二行合起来的最大子段和,如a21+a11, a22+a12, a23+a13 的最大子段和,再求第一到第三合起来的最大子段和,如a11+a21+a31, a12+a22+a32, a13+a23+a33的最大子段和…..以此类推,直到求出整个矩阵的合起来的最大子段和,求出他们之中最大的那个和就是解.

二、AC code

#include <stdio.h>
#include <stdlib.h>

int m[101][101];

int main()
{
    int n,max,i,j,k,tmp;

    while(scanf("%d",&n) != EOF)
    {
        max=-10000;
        /*
        输入时,顺便求出各行的最大字段和的最大值
        */
        for(i=0;i<n;++i)
        {
            tmp=0;
            for(j=0;j<n;++j)
            {
                scanf("%d",&m[i][j]);
                if(tmp>0)tmp+=m[i][j];
                else tmp=m[i][j];

                if(tmp>max)max=tmp;
            }
        }

        for(i=0;i<n-1;++i)
        {
            for(j=i+1;j<n;++j)
            {
                tmp=0;
                for(k=0;k<n;++k)
                {
                    //相当于把子矩阵多行压缩为一行了
                    m[i][k]+=m[j][k];
                    if(tmp>0)tmp+=m[i][k];
                    else tmp=m[i][k];

                    if(tmp>max)max=tmp;
                }
            }

        }
        printf("%d\n",max);
    }

    return 0;   
}
相关文章
F-POJ-3414 Pots
POJ-3414 Time Limit:1000 ms Memory Limit:65536 K Description You are given two po...
1009 0
POJ 1012 Joseph
Joseph Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 53862   Accepted: 20551 Description The Joseph's problem is notoriously known.
851 0
|
C语言
poj 2503 查字典
Description You have just moved from Waterloo to a big city. The people here speak an incomprehensible dialect of a foreign language.
879 0
|
机器学习/深度学习 算法
|
算法 机器人 编译器
POJ-2632
#include int main() { int k,a,b,n,m,i,j,num,rep,rect[100][100],robot[100][3]; int flag; char c; for(scanf("%d...
945 0
|
消息中间件 人工智能 JavaScript
|
算法 计算机视觉
最小割-poj-2914
poj-2914-Minimum Cut Description Given an undirected graph, in which two vertices can be connected by multiple edges, what is the size of the minimum cut of the graph? i.e. how many edges must b
1574 0