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
2진탐색을 직접 구현했을때
#include <iostream>
#include <stack>
#include <algorithm>
#include <vector>
using namespace std;
int N = 0;
int M = 0;
int num = 0;
vector<int> vecA;
void binarySearch(int target);
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> N;
for (int i = 0; i < N; i++)
{
cin >> num;
vecA.push_back(num);
}
sort(vecA.begin(), vecA.end());
cin >> M;
for (int i = 0; i < M; i++)
{
cin >> num;
binarySearch(num);
}
}
void binarySearch(int target)
{
int low = 0;
int high = vecA.size() - 1;
while (low <= high)
{
int mid = (low + high) / 2;
if (target == vecA[mid])
{
cout << "1" << "\n";
return;
}
else if (target < vecA[mid])
{
high = mid - 1;
}
else if (target > vecA[mid])
{
low = mid + 1;
}
}
cout << "0" << "\n";
}
algorithm 헤더에서 제공되는 binary_search 함수를 이용했을때.
for (int i = 0; i < M; i++)
{
cin >> num;
if (binary_search(vecA.begin(), vecA.end(), num))
cout << "1" << "\n";
else
cout << "0" << "\n";
//binarySearch(num);
}
'STUDY > Baekjoon' 카테고리의 다른 글
[백준] 11650 c++ 좌표 정렬하기 (0) | 2022.08.21 |
---|---|
[백준] 10816 c++ 숫자 카드 2 (0) | 2022.08.19 |
[백준] 10773 c++ 제로 (0) | 2022.08.19 |
[백준] 10828 c++ 스택 (0) | 2022.08.19 |
[백준] 11047 c++ 동전 0 (0) | 2022.08.18 |