Given an N layers triangle in mathematic like the graph below

Description
Given an N layers triangle in mathematic like the graph below. There are many ways that you could walk from the top to the bottom of the triangle. Every step, you can walk from one point to its left below or right below. Your hurt is the total number added though the way you choose. Now, your mission is to calculate the minimum hurt you could get.

     2

     6 2

     1 8 4

     1 5 6 8

For example, at point 4, you could only walk to 6 (left below) or 8 (right below).


Input
The first line is a positive integer n, representing the height of triangle’s edge. (n < 1000)

The second line to n + 1 line, is the data of the triangle described above.


Output
The minimum number of the hurt you could get.


Sample Input
4
2
6 2
1 8 4
1 5 6 8
Sample Output
10


深搜遍历
#include <iostream>
using namespace std;

int n;
int** arr;
int hurt;
int hurtsum;

void dfs(int x,int y,int hurt){
	//cout<<x<<" "<<y<<" "<<hurt<<endl;
	if(x==n-1){
		hurt+=arr[x][y];
		if(hurtsum>hurt){
			hurtsum=hurt;
		}
		return;
	}

	
	dfs(x+1,y,hurt+arr[x][y]);
	dfs(x+1,y+1,hurt+arr[x][y]);

}


int main(){
	hurt=0;
	hurtsum=0;
	cin>>n;
	arr=new int*[n];
	int j=0;
	for(int i=0;i<n;i++){
		arr[i]=new int[n];
		for(j=0;j<=i;j++){
			cin>>arr[i][j];
			hurtsum+=arr[i][j];
		}
		for(;j<n;j++){
			arr[i][j]=0;
		}
	}
	int x=0;
	int y=0;

	dfs(x,y,hurt);
	cout<<hurtsum;
	//system("pause");
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值