Saturday, April 16, 2016

【NEFU】17-数字三角形

Problem here

Problem


3 8 
8 1 0 
2 7 4 4 
4 5 2 6 5 
给出了一个数字三角形。从三角形的顶部到底部有很多条不同的路径。对于每条路径,把路径上面的数加起来可以得到一个和,你的任务就是找到最大的和。 
注意:路径上的每一步只能从一个数走到下一层上和它最近的左边的那个数或者右边的那个数。

INPUT

输入数据有多组,每组输入的是一行是一个整数N (1 < N <= 100),给出三角形的行数。下面的N行给出数字三角形。数字三角形上的数的范围都在0和100之间。

OUTPUT

输出最大的和。

Sample

input



3 8 
8 1 0 
2 7 4 4 
4 5 2 6 5 


2 3 
1 1 1

output

30 
5

Solution


3 8 
8 1 0 
2 7 4 4 
4 5 2 6 5 
以這個為例 
設x,y為位置 
則f(x,y)為到了(x,y)時的路徑長度 
所以可以得知 
f(1,1) = 7 <—第一個數嘛 
f(1+1, 1)=f(1,1)+f(1+1,1)=10 
f(1+1,1+1)=f(1,1)+f(1+1,1+1)=15 
f(3,1)= f(2,1)+f(3,1)=18 
f(3,2)=max(10,15)+1=16 
由此可知 
f(x,y)=max(f(x-1,y), f(x-1,y-1))+f(x,y)
#include <iostream>
#include <algorithm>
#include <memory.h>
using namespace std;

int main(){
    int n;
    while(cin >> n){
        int tg[101][101];
        memset(tg, 0, sizeof(tg));
        cin >> tg[1][1];
        for(int i = 2; i <= n; i++){
            for(int j = 1; j <= i; j++){
                cin >> tg[i][j];
                tg[i][j] = max(tg[i-1][j], tg[i-1][j-1]) + tg[i][j];
            }
        }
        int max = 0;
        for(int i = 1; i <= n; i++){
            for(int j = 1; j <= n; j++){
                if(max < tg[i][j]){
                    max = tg[i][j];
                }
            }
        }
        cout << max << endl;
    }
    return 0;
}

No comments:

Post a Comment