백준 10815 [c++] 숫자 카드

Roh·2023년 2월 22일
0

c++에서는 binary search를 직접 구현하지 않아도 된다.
binary_search() 함수 사용법을 알아보자.
아래 사진은 binary_search() 함수의 정의이며

binary_search(_FwdIt _First, _FwdIt _Last, const _Ty& _val) 

3개의 매개변수에 맞는 인수들을 넣어 주면 된다.

vector<int> v;

벡터에서 원하는값 x를 찾아주고 싶으면 아래와 같이 사용해주면 된다.

binary_search(v.begin(), v.end(), x)

그러면 아래에 있는 이 코드를 어렵지 않게 이해할 수 있을것이다.
binary_search()를 사용하기전에 sort()를 이용해 정렬해주어야한다.

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

using namespace std;

int n, m;

vector<int> db;
vector<int> v;

int main() {

	cin >> n;
	while (n--)
	{
		int tmp;
		cin >> tmp;
		db.push_back(tmp);
	}

	cin >> m;
	while (m--)
	{
		int tmp;
		cin >> tmp;
		v.push_back(tmp);
	}

	sort(db.begin(), db.end());

	for (int i = 0; i < v.size(); i++) {
		if (binary_search(db.begin(), db.end(), v[i]))
			cout << '1';
		else
			cout << '0';
		cout << ' ';
	}


	return 0;
}
profile
Better than doing nothing

0개의 댓글