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;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章