[BOJ][10815] 숫자 카드
Updated:
1. 문제 링크
https://www.acmicpc.net/problem/10815
2. 사용 알고리즘
이분 탐색
3. 풀이
이분 탐색을 통해 보유여부 확인
4. 소스 코드
4-1. C++
https://github.com/dev-aiden/problem-solving/blob/main/boj/10815.cpp
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
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <algorithm>
using namespace std;
int n, m;
int arr[500003], arr2[500003];
int bSearch(int num) {
int start = 0, end = n - 1;
while(start <= end) {
int mid = (start + end) / 2;
if(arr[mid] == num) {
return 1;
} else if(arr[mid] > num) {
end = mid - 1;
} else if(arr[mid] < num) {
start = mid + 1;
}
}
return 0;
}
int main(void) {
ios_base::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
cin >> n;
for(int i = 0; i < n; ++i) cin >> arr[i];
sort(arr, arr + n);
cin >> m;
for(int i = 0; i < m; ++i) cin >> arr2[i];
for(int i = 0; i < m; ++i) cout << bSearch(arr2[i]) << " ";
cout << "\n";
return 0;
}
4-2. JAVA
https://github.com/dev-aiden/problem-solving/blob/main/boj/10815.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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main {
static int n, m;
static int[] arr = new int[500003];
static int[] arr2 = new int[500003];
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
n = Integer.parseInt(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine());
for(int i = 0; i < n; ++i) arr[i] = Integer.parseInt(st.nextToken());
Arrays.sort(arr, 0, n);
m = Integer.parseInt(br.readLine());
st = new StringTokenizer(br.readLine());
for(int i = 0; i < m; ++i) arr2[i] = Integer.parseInt(st.nextToken());
StringBuilder sb = new StringBuilder();
for(int i = 0; i < m; ++i) sb.append(bSearch(arr2[i])).append(" ");
sb.append("\n");
System.out.println(sb);
}
public static int bSearch(int num) {
int start = 0, end = n - 1;
while(start <= end) {
int mid = (start + end) / 2;
if(arr[mid] == num) {
return 1;
} else if(arr[mid] > num) {
end = mid - 1;
} else if(arr[mid] < num) {
start = mid + 1;
}
}
return 0;
}
}
Leave a comment