Updated:

1. 문제 링크

https://www.acmicpc.net/problem/9461

2. 사용 알고리즘

DP

3. 풀이

d[n] : n 번째 정삼각형 변의 길이

위 그림에서 알 수 있듯이 인접한 두 개 삼각형의 변의 길이를 더하면 N의 길이가 된다.

∴ d[n] = d[n - 5] + d[n - 1]

4. 소스 코드

4-1. C++

4-1-1. Top-Down

https://github.com/dev-aiden/problem-solving/blob/main/boj/9461.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

using namespace std;

long long d[103];

long long solve(int n) {
    if (n <= 3) return 1;
    if (n <= 5) return 2;
    if (d[n] > 0) return d[n];
    return d[n] = solve(n - 5) + solve(n - 1);
}

int main(void) {
    ios_base::sync_with_stdio(false);
    int t; for (cin >> t; t--;) {
        int n; cin >> n;
        cout << solve(n) << "\n";
    }
    return 0;
}

4-1-2. Bottom-Up

https://github.com/dev-aiden/problem-solving/blob/main/boj/9461_2.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

using namespace std;

long long d[103];

int main(void) {
    ios_base::sync_with_stdio(false);
    d[1] = d[2] = d[3] = 1; d[4] = d[5] = 2;
    for (int i = 6; i <= 100; ++i) d[i] = d[i - 5] + d[i - 1];
    int t; for (cin >> t; t--;) {
        int n; cin >> n;
        cout << d[n] << "\n";
    }
    return 0;
}

4-2. JAVA

4-2-1. Top-Down

https://github.com/dev-aiden/problem-solving/blob/main/boj/9461.java

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
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {

    static long[] d = new long[103];

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();
        for(int t = Integer.parseInt(br.readLine()); t-- > 0;) {
            int n = Integer.parseInt(br.readLine());
            sb.append(solve(n)).append("\n");
        }
        System.out.println(sb);
    }

    public static long solve(int n) {
        if (n <= 3) return 1;
        if (n <= 5) return 2;
        if (d[n] > 0) return d[n];
        return d[n] = solve(n - 5) + solve(n - 1);
    }
}

4-2-2. Bottom-Up

https://github.com/dev-aiden/problem-solving/blob/main/boj/9461_2.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {

    static long[] d = new long[103];

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();
        d[1] = d[2] = d[3] = 1; d[4] = d[5] = 2;
        for(int i = 6; i <= 100; ++i) d[i] = d[i - 5] + d[i - 1];
        for(int t = Integer.parseInt(br.readLine()); t-- > 0;) {
            int n = Integer.parseInt(br.readLine());
            sb.append(d[n]).append("\n");
        }
        System.out.println(sb);
    }
}

Updated:

Leave a comment