๐Ÿ•๏ธ 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;
}
๋ฐ˜์‘ํ˜•