binary_search, lower_bound, upper_bound
μ λ ¬λμ΄ μλ λ°°μ΄, 컨ν μ΄λ λ±μ λμμΌλ‘ νμνλ€.
- binary_search: νμ λμμ΄ λλ κ°μ΄ μ‘΄μ¬νλμ§ νμΈνκ³ λ€μ΄ μλ€λ©΄ true, μλ€λ©΄ falseλ₯Ό λ°ννλ€.
- lower_bound: μ°Ύκ³ μ νλ κ° μ΄μμ΄ μ²μ λνλλ μμΉλ₯Ό λ°ννλ€.
- upper_bound: μ°Ύκ³ μ νλ κ°μ μ΄κ³Όνλ κ°μ΄ μ²μ λνλλ μμΉλ₯Ό λ°ννλ€.
λ¬Έμ
https://www.acmicpc.net/problem/12015
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(void)
{
int N;
cin >> N;
vector<int> v;
for (int i = 0; i < N; i++) {
int n;
cin >> n;
auto iter = lower_bound(v.begin(), v.end(), n);
if (iter == v.end())
v.push_back(n);
else
*iter = n;
}
cout << v.size();
}
λ¬Έμ : μ°Ύκ³ μ νλ κ°μ κ°μ ꡬνκΈ°
https://www.acmicpc.net/problem/10816
#include <iostream>
#include <algorithm>
using namespace std;
int num[500001];
int main()
{
int N;
cin >> N;
for (int i = 0; i < N; ++i)
cin >> num[i];
sort(num, num + N);
int M, tmp;
cin >> M;
for (int i = 0; i < M; ++i) {
cin >> tmp;
cout << upper_bound(num, num + N, tmp) - lower_bound(num, num + N, tmp) << " "; // κ°μ ꡬνκΈ°
}
}
https://www.acmicpc.net/problem/7453
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n;
cin >> n;
vector<int> A(n), B(n), C(n), D(n);
for (int i = 0; i < n; i++)
cin >> A[i] >> B[i] >> C[i] >> D[i];
vector<int> sumA, sumB;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
sumA.push_back(A[i] + B[j]);
sumB.push_back(C[i] + D[j]);
}
sort(sumA.begin(), sumA.end());
sort(sumB.begin(), sumB.end());
long long ans = 0;
for (int i = 0; i < sumA.size(); i++)
ans += upper_bound(sumB.begin(), sumB.end(), -sumA[i]) - lower_bound(sumB.begin(), sumB.end(), -sumA[i]);
cout << ans;
return 0;
}