zoukankan      html  css  js  c++  java
  • Ural 1146 Maximum Sum(DP)

    题目地址:Ural 1146

    这题是求最大子矩阵和。方法是将二维转化一维。

    首先用n*n的方法来确定矩阵的列。须要先进行预处理,仅仅对每行来说,转化成一维的前缀和,这样对列的确定仅仅须要前后两个指针来确定。仅仅须要用前缀和相减就可以得到。前后两个指针用n*n的枚举。

    确定好了哪几列,那么再确定行的时候就转化成了一维的最大连续子序列的和。

    再来一次O(n)的枚举就能够。

    这样,总复杂就变成了O(n^3)。对于n为100来说,已经足够了。

    代码例如以下:

    #include <iostream>
    #include <cstdio>
    #include <string>
    #include <cstring>
    #include <stdlib.h>
    #include <math.h>
    #include <ctype.h>
    #include <queue>
    #include <map>
    #include <set>
    #include <algorithm>
    
    using namespace std;
    const int INF=0x3f3f3f3f;
    #define LL long long
    int dp[200][200];
    int main()
    {
        int n, i, j, k, sum, x, max1;
        while(scanf("%d",&n)!=EOF)
        {
            max1=-INF;
            memset(dp,0,sizeof(dp));
            for(i=1;i<=n;i++)
            {
                for(j=1;j<=n;j++)
                {
                    scanf("%d",&x);
                    dp[i][j]=dp[i][j-1]+x;
                }
            }
            for(i=1;i<=n;i++)
            {
                for(j=0;j<i;j++)
                {
                    sum=0;
                    for(k=1;k<=n;k++)
                    {
                        sum+=dp[k][i]-dp[k][j];
                        max1=max(max1,sum);
                        if(sum<0) sum=0;
                    }
                }
            }
            printf("%d
    ",max1);
        }
        return 0;
    }
    


  • 相关阅读:
    九度oj 题目1208:10进制 VS 2进制
    九度oj 题目1209:最小邮票数
    九度oj 题目1207:质因数的个数
    九度oj 题目1030:毕业bg
    九度oj 题目1014:排名
    九度oj 题目1048:判断三角形类型
    九度oj 题目1335:闯迷宫
    [Luogu] Tree
    点分治 算法学习 && [Poj] 1741
    [Luogu] 排序机械臂
  • 原文地址:https://www.cnblogs.com/gcczhongduan/p/5261310.html
Copyright © 2011-2022 走看看