최대 1 분 소요

Question

Question


Solution

  • n에 대한 카드 정보를 vector에 담는다.
  • 이분 탐색 사용을 위해 sort()를 한다.
  • m의 카드가 n에 대한 vector에 있으면 1, 없으면 0을 출력.
  • 이중 for문을 사용하여 탐색을 하면 시간초과가 뜬다.

Cord

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    // n 카드 입력
    int n, m, num;
    vector<int> v;
    cin >> n;
    for (int idx = 0; idx < n; idx++)
    {
        cin >> num;
        v.push_back(num);
    }

    // 이분 탐색을 위한 정렬 실행
    sort(v.begin(), v.end());

    // m 카드 입력
    cin >> m;
    for (int idx = 0; idx < m; idx++)
    {
        cin >> num;
        
        // 이분 탐색
        cout << binary_search(v.begin(), v.end(), num) << ' ';
    }

    return 0;
}

Result

Result


What`s new

num이 v에 있는지 이분 탐색법으로 1 또는 0을 반환한다.

binary_search(v.being(), v.end(), num);