动态规划:ZOJ1074-最大和子矩阵 DP(最长子序列的升级版)
来源:互联网 发布:韦德生涯数据更新 编辑:程序博客网 时间:2024/06/06 07:46
To the Max
Time Limit:1 Second Memory Limit:32768 KB
Problem
Given a two-dimensional array of positive and negative integers, a sub-rectangle is any contiguous sub-array of size 1 x 1 or greater located within the whole array. The sum of a rectangle is the sum of all the elements in that rectangle. In this problem the sub-rectangle with the largest sum is referred to as the maximal sub-rectangle.
As an example, the maximal sub-rectangle of the array:
0 -2 -7 0
9 2 -6 2
-4 1 -4 1
-1 8 0 -2
is in the lower left corner:
9 2
-4 1
-1 8
and has a sum of 15.
The input consists of an N x N array of integers. The input begins with a single positive integer N on a line by itself, indicating the size of the square two-dimensional array. This is followed by N 2 integers separated by whitespace (spaces and newlines). These are the N 2 integers of the array, presented in row-major order. That is, all numbers in the first row, left to right, then all numbers in the second row, left to right, etc. N may be as large as 100. The numbers in the array will be in the range [-127,127].
Output
Output the sum of the maximal sub-rectangle.
Example
Input
4
0 -2 -7 0 9 2 -6 2
-4 1 -4 1 -1
8 0 -2
Output
15
解题心得:1、是一个很明显的动态规划,但是一开始的思路有点混乱,所以在处理的时候可以参照一下的方法:在输入的时候就将矩阵中的每一个数改写为同一行中前面I个数的和(这样才能处理子矩阵)。在处理列的时候数字就已经是行的和,这样就可以得到矩阵的和,所以处理子矩阵行的时候只能使用循环得出答案,记录最大的那个子矩阵。2、在做动态规划的题的时候首先要看出这个题是否可以用动态规划的思想来进行处理,在感觉普通思路行不通的时候可以试着用动态规划的思想来试试。3、在确定使用动态规划的时候就可以开始推动态转移(注意记录状态,先想最简单的转移,再逐步优化)的方程式,在数据不是很方便的时候可以改写一下数据。例如改写成 几 个数据的和,差。
#include<bits/stdc++.h>using namespace std;const int maxn = 150;int maps[maxn][maxn];int main(){ int n,sum,Max; while(~scanf("%d",&n)) { memset(maps,0,sizeof(maps)); Max = -1000000; for(int i=1;i<=n;i++)//考虑为什么要从1开始输入 for(int j=1;j<=n;j++) { int t; scanf("%d",&t); maps[i][j] = maps[i-1][j] + t;//将每一个数改为每一列的和 } for(int i=1;i<=n;i++) { for(int j=i;j<=n;j++) { sum = 0; for(int k=1;k<=n;k++) { int K; K = maps[j][k]-maps[i-1][k]; sum += K;//处理列的方法 sum = max(sum,0);//当sum小于0的时候可以直接舍去,参考最长子序列 Max = max(Max,sum);//记录最大的那个子矩阵的和 } } } printf("%d\n",Max); } return 0;}
阅读全文
0 0
- 动态规划:ZOJ1074-最大和子矩阵 DP(最长子序列的升级版)
- ZOJ1074 最大和子矩阵 DP最大连续子序列
- ZOJ1074 最大和子矩阵 DP
- hdu1081 最大子矩阵和(DP动态规划 最大子序列和变形题)
- 动态规划——最长连续子序列和+最大子矩阵和
- 最大子序列和+最大子矩阵-动态规划-无
- 算法篇-3-动态规划-矩阵连乘&最长公共子序列&最大字段和
- 【动态规划】最大连续序列和最大子矩阵
- 动态规划 最大子矩阵的和
- 动态规划之最长公共子序列和最长公共字串,最大子序列和
- 最长公共子序列-动态规划DP
- 最长共同子序列 --- DP(动态规划)
- 最长上升子序列 动态规划 dp
- LCS(最长公共子序列)和dp(动态规划)
- 最大子矩阵 动态规划DP
- 动态规划实现最大连续子序列和,最长不下降子序列和最长公共子序列
- [动态规划]最大子序列+最大子矩阵
- 最大连续子序列----DP动态规划
- Android Camera fw学习(三)-startPreview流程分析
- 1、redis入门
- Android EditText的设置错误提示信息
- android Audio OverView之三(driver)
- Leetcode 268 Missing Number
- 动态规划:ZOJ1074-最大和子矩阵 DP(最长子序列的升级版)
- Leetcode 414 Third Maximum Number
- POJ 2316 SPIN 笔记
- MyBatis学习之全局配置文件中各个标签的用途
- Fedora和Ubuntu下安装OpenGL开发环境配置
- Leetcode 485 Max Consecutive Ones
- 单例模式写法
- 欢迎使用CSDN-markdown编辑器
- PHP 7 的几个新特性和使用的代码