Project Euler18题 从上往下邻接和

题目: By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.

3
7 4
4 6
8 5 9 3

That is, 3 + 7 + 4 + 9 = 23.

Find the maximum total from top to bottom of the triangle below:

75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91 43 58 50 27 29 48
63 66 04 68 89 53 67 30 73 16 69 87 40 31
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23

这题的大概意思是从上往下求和,一个数字可以选下一行两个数字中的一个,求最大的和。

分析:这题我是没有思路的,我是网上抄了份答案过的题目,看了那些外国程序猿给的程序,有了些思路,写下来做点记录。这题从上往下不好做,但也可以做,只是比从下往上麻烦。我的思路是,把下面的每一行加到上面去,这样就不用管下面那一行具体的内容了。比如最后一行,倒数第二行的63,它下去能取到04、62两个数字,选取两数中大的那个加到63,同理把62和98中的大者加到66,......,直到把最后一行遍历完,全部加到倒数第二行,然后对倒数第二行执行同样的操作,直到第一行就是我们要求的结果。

代码:

// test18_.cpp : 定义控制台应用程序的入口点。
//看了别人的程序,似乎对这个题有一定的理解了。
/*
分析:这题要求计算的是从上往下邻接数据相加和的最大值,如果从上往下做这道题的话,就只能遍历所有数据,走遍
所有路径来确定最大值。换一种思路,从下往上分析。首先最后一行,把这一行的数据添加到倒数第二行去,然后把倒数第二行的数据
添加到倒数第三行去,往上叠加的方式。
*/

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <iomanip>

using namespace std;

int main()
{
	ifstream File("data.txt");
	string line;
	//开辟二维数组空间
	int n=15;
	int **data;
	data=new int *[n];
	//for(int i=0; i<n; i++)
	//{
	//	data[i]=new int [n];
	//}
	int i=0;
	int j;
	if(File.is_open())
	{
		while(getline(File,line))
		{	
			data[i]=new int[i+1];
			//cout<<line<<endl;
			stringstream ss(line);
			j=0;
			while(ss>>data[i][j])
			{
				j++;
			}
			++i;
		}
	}
	//把数组打印出来
	for(int i=0; i<n; i++)
	{
		for(int j=0; j<i+1; j++)
		{
			cout<<setw(2)<<data[i][j]<<" ";
		}
		cout<<endl;
	}
	for(int i=n-2; i>=0; i--)
	{
		for(j=0; j<i+1; j++)
		{
			if(data[i+1][j]>data[i+1][j+1])
			{
				data[i][j]=data[i][j]+data[i+1][j];
			}
			else
			{
				data[i][j]=data[i][j]+data[i+1][j+1];
			}
		}
	}
	//
	cout<<"最大的路径和为"<<data[0][0]<<endl;
	//释放空间
	for(int i=0; i<n; i++)
	{
		delete []data[i];
	}
	delete []data;
	system("pause");
	return 0;
}
结果:




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值