Algorithm, Data structure/Solved Algorithmic Problem

USACO 1.5 - Number Triangles

JaykayChoi 2016. 6. 27. 23:00

Consider the number triangle shown below. Write a program that calculates the highest sum of numbers that can be passed on a route that starts at the top and ends somewhere on the base. Each step can go either diagonally down to the left or diagonally down to the right.

          7

        3   8

      8   1   0

    2   7   4   4

  4   5   2   6   5

In the sample above, the route from 7 to 3 to 8 to 7 to 5 produces the highest sum: 30.

PROGRAM NAME: numtri

INPUT FORMAT

The first line contains R (1 <= R <= 1000), the number of rows. Each subsequent line contains the integers for that particular row of the triangle. All the supplied integers are non-negative and no larger than 100.

SAMPLE INPUT (file numtri.in)

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

OUTPUT FORMAT

A single line containing the largest sum using the traversal specified.

SAMPLE OUTPUT (file numtri.out)

30



출처: http://train.usaco.org/


전에 project euler 에서 풀었던 문제와 같은 문제네요.

삼각형의 꼭대기부터 아래쪽으로 인접한 숫자를 찾아 내려가면서 합을 구한다고 할 때 가장 합을 구하는 문제입니다.


삼각형의 제일 밑에서부터 올라가며 더하는 방법과 memoization 을 통해 시간 복잡도를 줄이고, y 축의 배열은 모두 저장할 필요 없이 바로 밑에 칸의 값만 가지고 있으면 된다는 점을 통해 공간 복잡도를 줄였습니다. 




my solving

c++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <fstream>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
 
const int MAX = 1000;
int numbers[MAX][MAX];
int cache[2][MAX];
int n;
 
int dynamicProgramming()
{
    for (int x = 0; x < n; x++)
        cache[(n - 1) % 2][x] = numbers[n - 1][x];
 
    for (int y = n - 2; y >= 0; y--)
    {
        for (int x = 0; x < y + 1; x++)
            cache[y % 2][x] = max(cache[(y + 1) % 2][x], cache[(y + 1) % 2][x + 1]) + numbers[y][x];
    }
 
    return cache[0][0];
}
 
int main()
{
    ifstream fin("numtri.in");
    ofstream fout("numtri.out");
 
    fin >> n;
 
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < i + 1; j++)
            fin >> numbers[i][j];
    }
 
    fout << dynamicProgramming() << endl;
 
    fin.close();
 
    return 0;
}
cs