이분 탐색(Binary Search)

백준 1920번: 수 찾기

cepiloth 2018. 6. 30. 16:30
반응형

https://www.acmicpc.net/problem/1920


1. 문제

N개의 정수 A[1], A[2], …, A[N]이 주어져 있을 때, 이 안에 X라는 정수가 존재하는지 알아내는 프로그램을 작성하시오.


2. 알고리즘

키워드 - 정렬, 이분탐색


3. 코드


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <iostream>
#include <sstream>
#include <string>
#include <algorithm>
#include <functional>
#include <vector>
#include <list>
#include <queue>
#include <deque>
#include <map>
#include <set>
#include <stack>
 
using namespace std;
 
#define MAX_SIZE 100
#define INF 0x7fffffff
#define CENDL "\n"
/*
* @memory  - 1984 kb
* @time    - 0 ms
*/
int card[100001];
 
bool bs(int left, int right, int data){
    int mid = (left + right) / 2;
    bool result;
    if (left > right) {
        return false;
    }
    else {
        
        if (card[mid] == data) {
            return true;
        }
        else if (card[mid] > data){
            result = bs(left, mid - 1, data);
        }
        else if (card[mid] < data)
        {
            result = bs(mid + 1, right, data);
        }
 
        return result;
    }
}
 
int main() {
 
    cin.tie(0);
    std::ios::sync_with_stdio(false);
 
    int n; cin >> n;
    
    for(int i=0; i<n; i++) {
        cin >> card[i];
    }
 
    sort(card, card + n);
 
    int m; cin >> m;
    for (int i=0; i<m; i++) {
        int cand; cin >> cand;
 
        if (bs(0, n-1, cand)) {
            cout << << CENDL;
        } else {
            cout << << CENDL;
        }
    }
    return 0;
}
 
cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <functional>         // greater 사용 위해 필요  
#include <string>
#include <map>
#include <unordered_map>
#include <math.h>
using namespace std;
 
int main() {
    ios::sync_with_stdio(false); cin.tie(0);  // scanf 안쓸 경우 쓰세요. Cin 사용시
    int n , m;
 
    cin >> n;
 
    unordered_map<intint> mm;
 
    for(int i =0; i<n; i++) {
        int cand; cin>> cand;
        mm[cand] = 0;
    }
    
    cin >> m;
    for(int i =0; i<m; i++) {
        int cand; cin >> cand;
        if (mm.find(cand) != mm.end()) {
            cout << "1" << "\n";
        } else {
            cout << "0" << "\n";
        }
    }
 
    return 0;
}
cs


반응형