문제 (https://www.acmicpc.net/problem/1920)
1920번: 수 찾기
첫째 줄에 자연수 N(1 ≤ N ≤ 100,000)이 주어진다. 다음 줄에는 N개의 정수 A[1], A[2], …, A[N]이 주어진다. 다음 줄에는 M(1 ≤ M ≤ 100,000)이 주어진다. 다음 줄에는 M개의 수들이 주어지는데, 이 수들
www.acmicpc.net
이분 탐색이 잘 기억이 안 나서 전에 풀었던 문제들 글을 써보려 한다 🤦♀️
이 문제는 간단한 이분 탐색 문제로 숫자들의 존재 여부를 1/0으로 출력해주면 된다.
[소스코드]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* BOJ 1920번: 수 찾기 | |
2021-05-25 | |
Binary Search */ | |
#include <iostream> | |
#include <algorithm> | |
#define MAX 100000 | |
using namespace std; | |
int n, m, num; | |
int arr[MAX]; | |
void solution(int num){ | |
int start = 0; | |
int end = n - 1; | |
int mid; | |
while(start <= end){ | |
mid = (start + end) / 2; | |
if(arr[mid] == num){ | |
cout << 1 << "\n"; | |
return; | |
} | |
else if(arr[mid] < num){ | |
start = mid + 1; | |
} | |
else if(arr[mid] > num){ | |
end = mid - 1; | |
} | |
} | |
cout << 0 << "\n"; | |
return; | |
} | |
int main(){ | |
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); | |
bool flag = false; | |
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 >> num; | |
solution(num); | |
} | |
return 0; | |
} |

'ALGORITHM > BOJ' 카테고리의 다른 글
[BOJ] 2805번 나무 자르기 (C++) (0) | 2021.12.19 |
---|---|
[BOJ] 2521번 예산 (C++) (0) | 2021.12.19 |
[BOJ] 12904번 A와 B (C++) (0) | 2021.11.24 |
[BOJ] 2866번 문자열 잘라내기 (C++) (0) | 2021.11.18 |
[BOJ] 16234번 인구 이동 (C++) (0) | 2021.11.18 |