Post

[BaekJoon] 1904번 - 01타일 [Java][C++]

[BaekJoon] 1904번 - 01타일 [Java][C++]

문제 링크


1. 문제 풀이


001을 활용해서 만들 수 있는 $N$ 자리 수열의 개수를 구하는 문제로, $N$ 자리 수열의 끝은 00이거나 1인 두 가지 밖에 없는데, 00이 오는 경우는 $N-2$ 자리에서 00을 붙이는 경우만큼 존재하며, 1이 오는 경우는 $N-1$ 자리에서 1을 붙이는 경우만큼 존재한다. 따라서 두 경우의 합만큼이 $N$ 자리 수열을 만드는 개수가 된다.


2. 코드


1. 풀이 [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
26
import java.io.*;

public class Main {

    static final int MOD = 15746;

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        int N = Integer.parseInt(br.readLine());

        if (N == 1) {
            System.out.println(1);
            return;
        }

        int[] dp = new int[1 + N];
        dp[1] = 1;
        dp[2] = 2;
        for (int i = 3; i <= N; i++) {
            dp[i] = (dp[i - 2] + dp[i - 1]) % MOD;
        }

        System.out.println(dp[N]);
    }
}


2. 풀이 [C++]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <bits/stdc++.h>
using namespace std;

constexpr int MAXN = 1000000;
constexpr int MOD = 15746;

int dp[1 + MAXN] = {0, 1, 2};

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int n;
    cin >> n;

    for (int i = 3; i <= n; i++) {
        dp[i] = (dp[i - 2] + dp[i - 1]) % MOD;
    }

    cout << dp[n];
}

This post is licensed under CC BY 4.0 by the author.