数字三角形问题(最大路径、动态规划)

输入样例:

5

7

3 8

8 1 0

2 7 4 4

4 5 2 6 5

输出

30

#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <string.h>
using namespace std;
int main() {
	int mp[100][100];
	memset(mp,0,sizeof(mp));
	int n, i, j, maxs;
	maxs = -1;
	cin>>n;
	for(i = 1; i <= n; ++i) {
		for(j = 1; j <= i; ++j) {
			scanf("%d", &mp[i][j]);
		}
	}
	if(n==1) {
		cout<<mp[1][1]<<endl;
	} else {
		for(i = 2; i <= n; ++i) {
			for(j = 1; j <= i; ++j) {
				mp[i][j] = max(mp[i-1][j-1],mp[i-1][j]) + mp[i][j];
				if(mp[i][j] > maxs) {
					maxs = mp[i][j];
				}
			}
		}
		cout<<maxs<<endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/adusts/article/details/80221367