POJ1163 The Triangle用贪心方法和交替使用二维数组实现内存和时间优化
来源:互联网 发布:datetimeoffset mysql 编辑:程序博客网 时间:2024/05/21 06:29
第一次写博客,如有不妥,请见谅。
啥也不说,先贴代码。
The Triangle
Time Limit: 1000MS Memory Limit: 10000KTotal Submissions: 46937 Accepted: 28425
Description
73 88 1 02 7 4 44 5 2 6 5(Figure 1)
Input
Your program is to read from standard input. The first line contains one integer N: the number of rows in the triangle. The following N lines describe the data of the triangle. The number of rows in the triangle is > 1 but <= 100. The numbers in the triangle, all integers, are between 0 and 99.
Output
Your program is to write to standard output. The highest sum is written as an integer.
Sample Input
573 88 1 0 2 7 4 44 5 2 6 5
Sample Output
30
首解释题意,本题是要求从N*N的对角三角形从高位到低位,每个高位对应着每个低位和地位右侧的值,本题如果进行暴力的话,本题的空间复杂度大于或者接近N^2,但是本题每次进行运算时,实际有效的的行数,只有进行运算的行数和进行运算的上一行,也就是说,最大只有2*N处的内存,进行实际有效的运算,所以不如我们定义一个2*N的二位数组,通过量程for循环进行输入(每次输入的过程中,通过去与相应的行数与2进行取余数进行输入而实现数据在两行间的输入),并且,(在这里我要分析一下贪心的使用方法护着说原理:我们每次在本行输入的数,对应的相应的加法位都为另一行的对应列数和左侧数进行想加,所以,我们需要使用贪心查看左右的加法中的值中较大的值,来进行相加)使用贪心算法,进行加法与储存本次加法的最大值。在循环输入和贪心处理之后,我们会在本2*N的数组中取得所有行列中,相应加法的最大值,我们只需要进行排序或者遍历一遍数组,就可以获得所需要的最大值。
此处应该有代码
#include <iostream>#include <string.h>#include <stdlib.h>#include <algorithm>#define maxn 105;int a[2][maxn];using namespace std;int main(){int n;while(scnaf("%d",&n)==1){memset(a,0,sizeof(a));int k=0;for(int h=1;h<=n;h++){k=h%2;for(int l=1;l<=n;l++){scanf("%d",&a[k][l]);a[k][l]+=max(a[k^1][l-1],a[k^1][l]);//本处为贪心算法}}int fndMax=0;for(int i=1;i<=n;i++){fndMax=max(fndMax,a[n%2][i]);}printf("%d\n",fndMax); }return 0;}
1 0
- POJ1163 The Triangle用贪心方法和交替使用二维数组实现内存和时间优化
- POJ1163 The Triangle
- POJ1163:The Triangle
- POJ1163 The Triangle
- POJ1163 The Triangle 【DP】
- POJ1163 The Triangle
- POJ1163 The Triangle
- POJ1163 The Triangle
- POJ1163 The Triangle
- poj1163 the triangle 题解
- POJ1163 The Triangle
- POJ1163 The Triangle 题解
- POJ1163 The Triangle
- poj1163 dp the triangle
- POJ1163 The Triangle
- poj1163 The Triangle
- poj1163 The Triangle
- The Triangle(poj1163)
- pat-bl-1032
- Android 实现分页功能中的计算总页数小算法
- Android Studio实现远程服务
- 原始的jdbc连接数据库以及操作(小总结)
- Eigen教程7 - Eigen和Matlab的比较
- POJ1163 The Triangle用贪心方法和交替使用二维数组实现内存和时间优化
- Windows下利用Cygwin搭建C/C++开发环境GCC
- js发布——订阅模式的通用实现及取消订阅
- HDU 2546 饭卡(01背包)
- 路由器硬改内存笔记1-理论
- 年会之事
- 二分查找—有序顺序表
- java从字符串中提取非数字
- 【C++ API】binary_function与unary_function使用详解