数字三角形

本博客介绍了一个关于数三角形的算法问题,目的是找到从顶点到底边的最大路径和。通过两种方法实现这一目标,一种是从上往下走,另一种是从下往上走。详细解释了每种方法的实现过程,并提供了相应的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The Triangle

时间限制:1000 ms  |  内存限制:65535 KB
难度:4
描述

7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
(Figure 1)
Figure 1 shows a number triangle. Write a program that calculates the highest sum of numbers passed on a route that starts at the top and ends somewhere on the base. Each step can go either diagonally down to the left or diagonally down to the right.

输入
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.
输出
Your program is to write to standard output. The highest sum is written as an integer.
样例输入
5
7
3 8
8 1 0 
2 7 4 4
4 5 2 6 5

样例输出:

30

题目大意:

给出一个数n,表示这个数字三角形有n层,每层的数字个数逐层递增。从第一行的数开始,每次可以往右下或左下走一格,直到走到最后一行,把沿途经过的数都加起来,如何走使得这个数最大?

思想:

方法一思想:从上往下走——将数字三角形存储在二维数组里,对每一个数组元素a[i][j]它要不加上正上方元素a[i-1][j],要不加上左上方元素a[i-1][j-1] 。即a[i][j]=Max(a[i-1][j],a[i-1][j-1] )+a[i][j].

代码如下:

<span style="font-size:18px;">#include <stdio.h>

int main(void)
{
	int a[101][101]={0};
	int n;
	int i,j,max;
	scanf("%d",&n);
	
	for(i=1;i<=n;i++)
	{
		for(j=1;j<=i;j++)
			scanf("%d",&a[i][j]);
	}
	for(i=1;i<=n;i++)
	{
		for(j=1;j<=i;j++)
		{
			if(a[i-1][j]>=a[i-1][j-1])
				a[i][j]+=a[i-1][j];
			else
				a[i][j]+=a[i-1][j-1];	
		}
	}
	i=n;
	max=a[n][1];
	for(j=2;j<=n;j++)
	{
		if(a[n][j]>max)
			max=a[n][j];
	}
	printf("%d",max);
	return 0;
} </span>


方法二思想

从下往上走——定义一个二维数组a[n+1][n+1],给最后一行初始化为数字三角形的最后一层,然后从底部往上顶走,直到走到顶部剩一个元素则为最大值。对数组元素a[i][j](i从n-1开始,i--到1.j从1开始,j++到n)它要不加上正下方元素a[i+1][j],要不加上右下方元素a[i+1][j+1] 。即a[i][j]=Max(a[i+1][j],a[i+1][j+1]  )+a[i][j].

000000
030



02321


0201310

07121010 
045265

代码如下:

#include <stdio.h>

int main(void)
{
	int a[101][101]={0};
	int b[101][101]={0};
	int n;
	int i,j,max;
	scanf("%d",&n);
	
	for(i=1;i<=n;i++)
	{
		for(j=1;j<=i;j++)
			scanf("%d",&a[i][j]);
	}
	//初始化 
	i=n;
	for(j=1;j<=n;j++)
		b[i][j]=a[i][j];
	//dp
	for(i=n-1;i>=1;i--)
	{
		for(j=1;j<=n;j++)
		{
			if(a[i+1][j]>=a[i+1][j+1])
				a[i][j]+=a[i+1][j];
			else
				a[i][j]+=a[i+1][j+1];	
		}
	}	

	printf("%d",a[1][1]);
	return 0;
} 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值