코드
#include <iostream>
#include <algorithm>
#include <vector>
// 이진 탐색 알고리즘 공식 참고
int binarySearch(std::vector<int>& _numvector, int _value) {//k
int low = 0;
int high = _numvector.size() - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (_numvector[mid] > _value)
{
high = mid - 1;
}
else if (_numvector[mid] < _value)
{
low = mid + 1;
}
else
{
return 1; // 찾는 값이 있는 경우
}
}
return 0; // 없는 경우
}
int main()
{
std::ios_base::sync_with_stdio(false);
std::cin.tie(nullptr);
std::vector<int> numvector;
int n, m;
std::cin >> n;
numvector.resize(n);
for (int i = 0; i < n; i++)
{
int inputn;
std::cin >> inputn;
numvector[i] = inputn;
}
std::cin >> m;
std::sort(numvector.begin(), numvector.end()); // 이진 탐색을 위한 정렬
for (int i = 0; i < m; i++)
{
int inputn;
std::cin >> inputn;
std::cout << binarySearch(numvector, inputn) << " ";
}
numvector.clear();
}
'C++ > 백준 C++' 카테고리의 다른 글
[C/C++] 백준 10816번 숫자 카드 2 (0) | 2024.06.03 |
---|---|
[C/C++] 백준 14425번 문자열 집합 (0) | 2024.05.31 |
[C/C++] 백준 2559번 수열 (0) | 2024.05.30 |
[C/C++] 백준 2563번 색종이 (0) | 2024.05.29 |
[C/C++] 백준 2566번 최댓값 (0) | 2024.05.29 |