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
이분 탐색으로 구현하였다. 이분 탐색 시작 전, 배열을 오름차순 정렬하는 걸 잊지말자!
#include <iostream>
#include <algorithm>
#include <cstdio>
using namespace std;
int N, M;
int n;
int arr[100000];
int solve(int n) {
int start = 0;
int end = N-1;
while (start <= end) {
int mid = (start + end) / 2;
if (arr[mid] == n) return 1;
else if (n < arr[mid]) end = mid - 1;
else start = mid + 1;
}
return 0;
}
int main() {
ios_base::sync_with_stdio(0); cin.tie(0);
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 >> n;
cout << solve(n) << "\n";
}
}
'Algorithm > 그리디' 카테고리의 다른 글
[프로그래머스] 광고삽입 (C++) (2021 KAKAO BLIND RECRUITMENT) (1) | 2021.10.02 |
---|---|
[백준] 1647번 : 도시 분할 계획 (0) | 2021.09.24 |
[백준] 1197번 : 최소 스패닝 트리 (C++) (0) | 2021.09.15 |
[백준] 8980번 : 택배 (C++) (0) | 2021.09.05 |
[백준] 1041번 : 주사위 (C++) (0) | 2021.08.22 |
댓글