zoukankan      html  css  js  c++  java
  • 37. Matrix

    题目描述

    现在你面对一个n×m的矩阵,矩阵中的每一个元素都是一个整数,现在你需要计算从矩阵的左上角走到右下角所走过的所有元素相加的最大和。
    注意:只能向右或者向下走,不能走出边界。

    解答要求时间限制:1000ms, 内存限制:100MB
    输入

    输入第一行包含两个用空格分开的整数n (1≤ n ≤ 100)和m (1≤ m ≤ 100),表示n行m列的矩阵;接下来是n行每行包含m个用空格分开的非负的整数A (0 ≤ A ≤ 100)。

    输出

    输出从矩阵的左上角走到右下角所走过的所有元素相加的最大和。

    样例

    输入样例 1 复制

    2 3
    1 2 3
    1 0 2

    输出样例 1

    8
    提示样例 1
     


    输入样例 2 复制

    5 3
    14 14 4
    76 5 76
    78 23 23
    45 75 53
    52 43 71

    输出样例 2

    412
    提示样例 2
     


    提示

    Sample test1中最大和为1+2+3+2=8。

    Sample test2最大和为14+76+78+45+75+53+71=412

    思路:动态规划
    代码:
    // we have defined the necessary header files here for this problem.
    // If additional header files are needed in your program, please import here.
    
    int main()
    { 
      // please define the C++ input here. For example: int a,b; cin>>a>>b;;  
      // please finish the function body here.  
      // please define the C++ output here. For example:cout<<____<<endl; 
      
       int matrix[105][105];
        int M,N;
        cin>>M>>N;
        for(int i =0 ;i<M;i++)
        {
            for(int j = 0;j<N;j++)
            {
                cin>>matrix[i][j];
            }
        }
        int dp[105][105];
        for(int i = 0;i<M;i++)
        {
            dp[i][0] = matrix[i][0];
        }
            for(int j = 0;j<M;j++)
        {
            dp[0][j] = matrix[0][j];
        }
        for(int i = 0;i<M;i++)
        {
            for(int j = 0;j<N;j++)
            {
                dp[i][j]=max(dp[i-1][j],dp[i][j-1])+matrix[i][j];
            }
        }
        cout<<dp[M-1][N-1]<<endl;
       return 0;
    }
    以大多数人努力程度之低,根本轮不到去拼天赋~
  • 相关阅读:
    TClientDataSet[7]: 辨析 Field、FieldDef、Fields、FieldDefs、FieldList、FieldDefList
    TClientDataSet[11]: 分组统计
    TClientDataSet[14]: 测试 FindFirst、FindNext、FindLast、FindPrior、Found
    TClientDataSet[9]: 计算字段和 State
    这两天的收获
    又去北京
    关于博客园融资的想法
    《别为小事抓狂》读书笔记
    下周将去北京寻找投资
    服务器搬迁预告
  • 原文地址:https://www.cnblogs.com/gcter/p/15472722.html
Copyright © 2011-2022 走看看