Post

[BaekJoon] #1475 - 방 번호 [Java][C++][Python]

[BaekJoon] #1475 - 방 번호 [Java][C++][Python]

문제 링크


1. 아이디어

방 번호의 모든 숫자를 만드는 데 필요한 세트 수의 최솟값을 구하는 문제이다. 한 세트에 0부터 9까지 하나씩 들어 있으므로 세트가 $s$개면 각 숫자를 $s$번까지 쓸 수 있고, 6과 9는 뒤집어 서로 대신할 수 있어 둘을 한 종류로 보면 세트마다 두 장이다. 6과 9의 총 개수를 $c$라 하면 이 종류에는 $\lceil c / 2 \rceil$세트가 필요하고, 나머지 숫자는 방 번호에 나온 횟수만큼의 세트가 필요하다. 모든 숫자를 동시에 만들어야 하므로 필요한 세트 수는 이 값들 중 최댓값이다.


2. 코드

풀이 [Java][C++][Python]

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

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

        int[] cnt = new int[10];
        for (char c : br.readLine().toCharArray()) {
            cnt[c - '0']++;
        }

        int max = 0;
        for (int i = 0; i < 10; i++) {
            if (i == 6 || i == 9) continue;
            max = Math.max(max, cnt[i]);
        }
        max = Math.max(max, (cnt[6] + cnt[9] + 1) / 2);

        System.out.println(max);
    }
}
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
#include <bits/stdc++.h>
using namespace std;

int cnt[10];

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

    string s;
    cin >> s;

    for (char c : s) {
        cnt[c - '0']++;
    }

    int mx = 0;
    for (int i = 0; i < 10; i++) {
        if (i == 6 || i == 9) continue;
        mx = max(mx, cnt[i]);
    }
    mx = max(mx, (cnt[6] + cnt[9] + 1) / 2);

    cout << mx;
}
1
2
3
4
5
6
7
8
9
10
11
import sys

input = sys.stdin.readline

s = input().rstrip()
cnt = [0] * 10
for c in s:
    cnt[int(c)] += 1
cnt[6] = (cnt[6] + cnt[9] + 1) // 2

print(max(cnt[:9]))

6과 9의 개수를 cnt[6]에 합쳐 올림해 두었으므로, 9를 따로 세지 않도록 cnt[:9]로 인덱스 8까지만 최댓값을 구했다.


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