第一次写博客,如有不妥,请见谅。
啥也不说,先贴代码。
The Triangle
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 46937 | Accepted: 28425 |
Description
7 3 8 8 1 0 2 7 4 4 4 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
5 7 3 8 8 1 0 2 7 4 4 4 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;
}