이분탐색
std::binary_search이분탐색 STL
<algorithm>true, 찾지 못하면 false를 반환하는 bool 타입template <class ForwardIterator, class T>
bool binary_search(ForwardIterator first, ForwardIterator last, const T& val);
// example
bool found30 = binary_search(v.begin(), v.end(), 30);
std::lower/upper_bound<algorithm>#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
// 이미 오름차순 정렬된 벡터 (20이 3개 중복되어 있음)
vector<int> v = {10, 20, 20, 20, 30, 40};
// 1. lower_bound: 20 "이상"이 처음 나오는 위치
auto lower = lower_bound(v.begin(), v.end(), 20);
// 2. upper_bound: 20을 "초과"하는 값이 처음 나오는 위치
auto upper = upper_bound(v.begin(), v.end(), 20);
// 3. 인덱스 구하기 (반복자에서 v.begin()을 뺌)
int lower_index = lower - v.begin();
int upper_index = upper - v.begin();
return 0;
}
조건을 만족하는 최소/최댓값을 구하는 문제, 즉 최적화 문제를 결정 문제로 변환해 이분탐색을 수행하는 방법
ex. 랜선 자르기 문제