본문 바로가기
PS

[C++] 백준 1920 - 수 찾기

by gamxong 2023. 3. 2.
백준 1920 : 수 찾기
난이도 : 실버 4
시간 : 20분 소요

 

 

 

문제

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

 

1920번: 수 찾기

첫째 줄에 자연수 N(1 ≤ N ≤ 100,000)이 주어진다. 다음 줄에는 N개의 정수 A[1], A[2], …, A[N]이 주어진다. 다음 줄에는 M(1 ≤ M ≤ 100,000)이 주어진다. 다음 줄에는 M개의 수들이 주어지는데, 이 수들

www.acmicpc.net


풀이 과정

 

이진 탐색을 활용한 간단한 문제이다.

 

 

최종 코드

#include <iostream>
#include <cstring>
#include <algorithm>

#define MAX 100001

using namespace::std;

int N, M;

int arr[MAX];
int fin[MAX];

bool check(int f, int b, int n){
    int mid = arr[(f+b)/2];
    if(mid == n){
        return true;
    }
    if(n<arr[f] || n>arr[b]){
        return false;
    }
    
    bool tmp = false;
    
    if(mid<n){
        tmp = check((f+b)/2+1, b, n);
    }else if(mid>n){
        tmp = check(0,(f+b)/2-1, n);
    }
    return tmp;
}

int main(){
    scanf("%d", &N);
    for(int i=0; i<N; i++){
        scanf("%d", &arr[i]);
    }
    sort(arr, arr+N);
    
    scanf("%d", &M);
    for(int i=0; i<M; i++){
        scanf("%d", &fin[i]);
        if(check(0, N-1, fin[i])){
            fin[i] = 1;
        }else{
            fin[i] = 0;
        }
    }
    
    for(int i=0; i<M; i++){
        printf("%d\n", fin[i]);
    }
}
 
 

'PS' 카테고리의 다른 글

[C++] 백준 25682 - 체스판 다시 칠하기 2  (0) 2023.03.03
[C++] 백준 11660 - 구간 합 구하기 5  (0) 2023.03.02
[C++] 백준 12865 - 평범한 배낭  (0) 2023.03.02
[C++] 백준 9251 - LCS  (0) 2023.03.02
[C++] 백준 1753 - 최단경로  (0) 2023.03.02

댓글