[BOJ] λ°±μ€ 10816λ²: μ«μ μΉ΄λ 2 (Map μμ΄ μ΄λΆνμλ§μΌλ‘ νκΈ°)
https://www.acmicpc.net/problem/10816
10816λ²: μ«μ μΉ΄λ 2
첫째 μ€μ μκ·Όμ΄κ° κ°μ§κ³ μλ μ«μ μΉ΄λμ κ°μ N(1 ≤ N ≤ 500,000)μ΄ μ£Όμ΄μ§λ€. λμ§Έ μ€μλ μ«μ μΉ΄λμ μ νμλ μ μκ° μ£Όμ΄μ§λ€. μ«μ μΉ΄λμ μ νμλ μλ -10,000,000λ³΄λ€ ν¬κ±°λ κ°κ³ , 10,
www.acmicpc.net
λ¬Έμ
μ«μ μΉ΄λλ μ μ νλκ° μ νμ Έ μλ μΉ΄λμ΄λ€. μκ·Όμ΄λ μ«μ μΉ΄λ Nκ°λ₯Ό κ°μ§κ³ μλ€. μ μ Mκ°κ° μ£Όμ΄μ‘μ λ, μ΄ μκ° μ νμλ μ«μ μΉ΄λλ₯Ό μκ·Όμ΄κ° λͺ κ° κ°μ§κ³ μλμ§ κ΅¬νλ νλ‘κ·Έλ¨μ μμ±νμμ€.
μ λ ₯
첫째 μ€μ μκ·Όμ΄κ° κ°μ§κ³ μλ μ«μ μΉ΄λμ κ°μ N(1 ≤ N ≤ 500,000)μ΄ μ£Όμ΄μ§λ€. λμ§Έ μ€μλ μ«μ μΉ΄λμ μ νμλ μ μκ° μ£Όμ΄μ§λ€. μ«μ μΉ΄λμ μ νμλ μλ -10,000,000λ³΄λ€ ν¬κ±°λ κ°κ³ , 10,000,000λ³΄λ€ μκ±°λ κ°λ€.
μ μ§Έ μ€μλ M(1 ≤ M ≤ 500,000)μ΄ μ£Όμ΄μ§λ€. λ·μ§Έ μ€μλ μκ·Όμ΄κ° λͺ κ° κ°μ§κ³ μλ μ«μ μΉ΄λμΈμ§ ꡬν΄μΌ ν Mκ°μ μ μκ° μ£Όμ΄μ§λ©°, μ΄ μλ 곡백μΌλ‘ ꡬλΆλμ΄μ Έ μλ€. μ΄ μλ -10,000,000λ³΄λ€ ν¬κ±°λ κ°κ³ , 10,000,000λ³΄λ€ μκ±°λ κ°λ€.
μΆλ ₯
첫째 μ€μ μ λ ₯μΌλ‘ μ£Όμ΄μ§ Mκ°μ μμ λν΄μ, κ° μκ° μ ν μ«μ μΉ΄λλ₯Ό μκ·Όμ΄κ° λͺ κ° κ°μ§κ³ μλμ§λ₯Ό 곡백μΌλ‘ ꡬλΆν΄ μΆλ ₯νλ€.
νμ΄ 1 - upperBound, lowerBound μ¬μ©
// Authored by : seondal
// Co-authored by : -
// #include <bits/stdc++.h>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
ios_base :: sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
int n, m;
cin >> n;
vector<int> arr(n,0);
for(int i=0; i<n; i++)
cin >> arr[i];
sort(arr.begin(), arr.end());
cin >> m;
int input;
while(m--) {
cin >> input;
int ans = upper_bound(arr.begin(), arr.end(), input) - lower_bound(arr.begin(), arr.end(), input);
cout << ans << "\n";
}
}
/*
*/
νμ΄2 - upperBound, lowerBound μ§μ ꡬν
// Authored by : seondal
// Co-authored by : -
// #include <bits/stdc++.h>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int lowerBound(int left, int right, int target, vector<int> &arr) {
while(left <= right) {
int mid = (left+right) /2;
if(arr[mid] >= target)
right = mid-1;
else
left = mid+1;
}
// 1. break μ§μ leftμ rightλ κ°μκ³³μ κ°λ¦¬ν΄
// 2. arr[mid] λ target λ³΄λ€ μκΈ° λλ¬Έμ left ν¬μΈν° μ΄λ
// 3. μ΄λν left ν¬μΈν°κ° = targetμ μΈλ±μ€ => return
return left;
}
int upperBound(int left, int right, int target, vector<int>&arr) {
while(left <= right) {
int mid = (left+right) / 2;
if(arr[mid] <= target)
left = mid+1;
else
right = mid-1;
}
// 1. arr[mid] <= targetμ΄λ©΄ left μ΄λ
// 2. arr[mid] == targetμ΄λ©΄ left = mid+1 ... left>target μΈ μκ° λ©μΆ€
// 3. μ΄λ left κ° = upperBound!
return left;
}
int main() {
ios_base :: sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
int n, m;
cin >> n;
vector<int> arr(n,0);
for(int i=0; i<n; i++)
cin >> arr[i];
sort(arr.begin(), arr.end());
cin >> m;
int input;
while(m--) {
cin >> input;
int ans = upperBound(0, n-1, input, arr) - lowerBound(0, n-1, input, arr);
cout << ans << "\n";
}
}
/*
*/