ποΈ PS (BOJ)/Binary Search
[BOJ][C++] λ°±μ€ 1920λ²: μ μ°ΎκΈ° (Silver IV)
μ λ¬
2025. 4. 22. 16:32
λ°μν
λ¬Έμ
Nκ°μ μ μ A[1], A[2], …, A[N]μ΄ μ£Όμ΄μ Έ μμ λ, μ΄ μμ XλΌλ μ μκ° μ‘΄μ¬νλμ§ μμλ΄λ νλ‘κ·Έλ¨μ μμ±νμμ€.
μ λ ₯
첫째 μ€μ μμ°μ N(1 ≤ N ≤ 100,000)μ΄ μ£Όμ΄μ§λ€. λ€μ μ€μλ Nκ°μ μ μ A[1], A[2], …, A[N]μ΄ μ£Όμ΄μ§λ€. λ€μ μ€μλ M(1 ≤ M ≤ 100,000)μ΄ μ£Όμ΄μ§λ€. λ€μ μ€μλ Mκ°μ μλ€μ΄ μ£Όμ΄μ§λλ°, μ΄ μλ€μ΄ Aμμ μ‘΄μ¬νλμ§ μμλ΄λ©΄ λλ€. λͺ¨λ μ μμ λ²μλ -231λ³΄λ€ ν¬κ±°λ κ°κ³ 231λ³΄λ€ μλ€.
μΆλ ₯
Mκ°μ μ€μ λ΅μ μΆλ ₯νλ€. μ‘΄μ¬νλ©΄ 1μ, μ‘΄μ¬νμ§ μμΌλ©΄ 0μ μΆλ ₯νλ€.
νμ΄
ios_base :: sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
μ΄λΆνμμΌλ‘ νλ©΄ ν리λλ° μ μΆλ ₯ μ΅μ ν μνλ©΄ μκ°μ΄κ³Ό λ¬λ€
#include <bits/stdc++.h>
using namespace std;
int ans(int n, vector<int>&a, int x) {
int start=0, end=n-1, mid;
while(start<=end) {
mid = (start+end)/2;
if(a[mid] == x) {
return 1;
}
if(a[mid] < x) {
start = mid+1;
} else {
end = mid-1;
}
}
return 0;
}
int main() {
ios_base :: sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
// input
int n;
cin >> n;
vector<int>a(n);
for(int i=0; i<n; i++) {
cin >> a[i];
}
int m;
cin >> m;
// solution
sort(a.begin(), a.end());
int x;
while(m--) {
cin >> x;
cout << ans(n, a, x) << "\n";
}
return 0;
}
λ°μν