[BaekJoon] #3052 - 나머지 [Java][C++][Python]
[BaekJoon] #3052 - 나머지 [Java][C++][Python]
1. 아이디어
수 10개를 42로 나눈 나머지 중 서로 다른 값이 몇 개인지 구하는 문제다.
방문 체크는 42로 나눈 나머지가 0부터 41까지 42가지뿐이라는 점을 쓴다. 크기 42의 배열에 나온 나머지를 표시하면 같은 나머지가 여러 번 나와도 한 칸만 표시되므로, 표시된 칸의 수가 곧 답이다.
해시셋은 같은 값을 한 번만 담으므로 나머지를 그대로 넣고 크기를 읽으면 되며, 나머지의 범위로 배열 크기를 정할 필요가 없다.
2. 코드
풀이 1: 방문 체크 [Java][C++][Python]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
boolean[] seen = new boolean[42];
for (int i = 0; i < 10; i++) {
int x = Integer.parseInt(br.readLine());
seen[x % 42] = true;
}
int cnt = 0;
for (boolean flag : seen) {
if (flag) cnt++;
}
System.out.println(cnt);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
vector<bool> seen(42);
for (int i = 0; i < 10; i++) {
int x;
cin >> x;
seen[x % 42] = true;
}
cout << count(seen.begin(), seen.end(), true);
}
std::count로 true인 칸의 수를 셌다.
1
2
3
4
5
6
7
8
9
10
import sys
input = sys.stdin.readline
seen = [False] * 42
for _ in range(10):
x = int(input())
seen[x % 42] = True
print(seen.count(True))
count로 리스트에 있는 True의 개수를 셌다.
풀이 2: 해시셋 [Java][C++][Python]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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> seen = new HashSet<>();
for (int i = 0; i < 10; i++) {
int x = Integer.parseInt(br.readLine());
seen.add(x % 42);
}
System.out.println(seen.size());
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
unordered_set<int> seen;
for (int i = 0; i < 10; i++) {
int x;
cin >> x;
seen.insert(x % 42);
}
cout << seen.size();
}
1
2
3
4
5
6
7
8
9
10
import sys
input = sys.stdin.readline
seen = set()
for _ in range(10):
x = int(input())
seen.add(x % 42)
print(len(seen))
This post is licensed under CC BY 4.0 by the author.