V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
sharonlyu
V2EX  ›  问与答

最大子矩阵和代码问题-动态规划

  •  
  •   sharonlyu · 2015-06-10 16:48:03 +08:00 · 1271 次点击
    这是一个创建于 3296 天前的主题,其中的信息可能已经有所发展或是发生改变。

    如题,最大子矩阵和问题,问题描述可参见POJ: http://poj.org/problem?id=1050

    我想提问的具体问题是压缩子矩阵为一行的循环起点和循环终点,我自己写的完整代码如下:
    int main(int argc, const char * argv[]) {
    // insert code here...
    // 最大子矩阵和问题
    // first get all the numbers from the user
    cout<<"Please first enter the dimension of this array as in N, then enter each one of the numbers in this array, with'enter's in between:";
    int N;
    cin>>N;
    int a[N][N];
    for (int i=1; i<=N; i++) {
    for (int j=1; j<=N; j++) {
    cin>>a[i][j];
    }
    }
    int SofArray=0;
    // for rectangles that have 1,2,3...,N rows, do the addition for each column
    for (int i=1; i<=N; i++) {
    //create the target row
    int targetRow[N];
    for (int j=1; j<=N; j++) {
    targetRow[j]=0;
    for (int k=1; k<=i; k++) {
    targetRow[j]+=a[k][j];
    }
    }

    //now do the 最大子段和 solution
        int S=0,b=0;
        for (int j=1; j<=N; j++) {
            if (b<0) {
                b=targetRow[j];
            }
            else {
                b+=targetRow[j];
            }
            if (b>=S) {
                S=b;
            }
        }
        // compare S and SofArray
        if (S>=SofArray) {
            SofArray=S;
        }
    }
    // give back the info to the user
    cout<<"The max sum of sub-rectangles of this array is:"<<SofArray<<endl;
    
    return 0;
    

    }

    (我是小白请勿嫌弃。。QAQ捂脸)

    有一个地方跟标准答案不一样。。。就是压缩成一行那里(正文第22行)。。。我是for (int k=1;k<=i;k++),就是k从1到i嘛,因为这里有i行j列呀。。。可是标准答案是for (int k=i;k<=N;k++),也就是k是从i到N了。。。就想知道这是为啥。。。先谢过!乃们都是大好人!!QAQ

    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   5136 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 07:58 · PVG 15:58 · LAX 00:58 · JFK 03:58
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.