๋ฐ์ํ
๋ฌธ์
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;
}
๋ฐ์ํ
'๐๏ธ PS (BOJ) > Binary Search' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[BOJ][C++] ๋ฐฑ์ค 3079๋ฒ: ์ ๊ตญ์ฌ์ฌ (Gold V) (0) | 2025.04.23 |
---|---|
[BOJ][C++] ๋ฐฑ์ค 10816๋ฒ: ์ซ์ ์นด๋ 2 (Silver IV) (0) | 2025.04.22 |
[BOJ][C++] ๋ฐฑ์ค 1365๋ฒ: ๊ผฌ์ธ ์ ๊น์ค (0) | 2024.09.30 |
[BOJ][C++] ๋ฐฑ์ค 1654๋ฒ: ๋์ ์๋ฅด๊ธฐ (0) | 2023.11.17 |
[BOJ][C++] ๋ฐฑ์ค 2805๋ฒ: ๋๋ฌด ์๋ฅด๊ธฐ (0) | 2023.11.06 |