Post

[백준] 3052번 - 나머지 [Java][C++]

[백준] 3052번 - 나머지 [Java][C++]

문제 링크


1. 문제 풀이

$42$ 로 나눈 겹치지 않는 나머지의 개수를 구하는 문제로 방문 체크 배열을 활용해서 해결할 수도 있고 집합을 활용해도 해결할 수 있다.


2. 코드

1. 사칙연산 [Java]

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));

        boolean[] visited = new boolean[42];
        for (int i = 0; i < 10; i++) {
            int num = Integer.parseInt(br.readLine());

            visited[num % 42] = true;
        }

        int cnt = 0;
        for (boolean flag : visited) {
            if (flag) cnt++;
        }

        System.out.println(cnt);
    }
}

2. 해시를 사용한 집합과 맵 [Java]

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

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

        Set<Integer> set = new HashSet<>();
        for (int i = 0; i < 10; i++) {
            int num = Integer.parseInt(br.readLine());

            set.add(num % 42);
        }

        System.out.println(set.size());
    }
}

3. 사칙연산 [C++]

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

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

    bool visited[42] = {};
    for (int i = 0; i < 10; i++) {
        int n;
        cin >> n;

        visited[n % 42] = true;
    }

    cout << count(visited, visited + 42, true);
}

4. 해시를 사용한 집합과 맵 [C++]

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

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

    unordered_set<int> st;
    for (int i = 0; i < 10; i++) {
        int n;
        cin >> n;

        st.insert(n % 42);
    }

    cout << st.size();
}

3. 풀이 정보

1. 사칙연산 [Java]

언어시간메모리코드 길이
Java 11100 ms14144 KB516 B

2. 해시를 사용한 집합과 맵 [Java]

언어시간메모리코드 길이
Java 11100 ms14148 KB435 B

3. 사칙연산 [C++]

언어시간메모리코드 길이
C++ 170 ms2020 KB301 B

4. 해시를 사용한 집합과 맵 [C++]

언어시간메모리코드 길이
C++ 170 ms2024 KB271 B

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