This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<iostream> | |
#include <vector> | |
#include<algorithm> | |
using namespace std; | |
vector<int> ary; | |
vector<int> ans; | |
vector<int>::iterator iter; | |
int search(int a, int left=0, int right=ary.size()-1){ | |
if(right<left){ | |
ans.push_back(0); | |
return 0; | |
} | |
int middle=(left+right)/2; | |
if(ary[middle]==a) ans.push_back(1); | |
else if(ary[middle]>a) search(a,0,middle-1); | |
else search(a,middle+1,right); | |
return 2; | |
}; | |
int main(){ | |
ios::sync_with_stdio(false); cout.tie(NULL); cin.tie(NULL); | |
int n,m,element; | |
cin>>n; | |
for(int i=0;i<n;i++){ | |
cin>>element; | |
ary.push_back(element); | |
} | |
sort(ary.begin(),ary.end()); | |
cin>>m; | |
while(m--){ | |
cin>>element; | |
search(element); | |
} | |
for(iter=ans.begin();iter!=ans.end();iter++){ | |
cout<<*iter<<"\n"; | |
} | |
} |
이원탐색(binary search)과 STL의 sort함수를 이용했다.
이원탐색은 재귀함수의 형태로 구현했고 ary vector를 통해 입력값을 받아 sort한 후 탐색을 통해 결과를 ans vector에 저장해 출력했다.
'ALG > ALG Solve' 카테고리의 다른 글
C++) 백준 1406번 - 에디터 (0) | 2023.01.11 |
---|---|
C++) 백준 11654번 - 아스키 코드 (0) | 2023.01.03 |
C++) 백준 2635번 수 이어가기 (0) | 2023.01.02 |
C++) 백준 2741번 - N찍기 (0) | 2023.01.02 |
C++) 백준 1408번 - 24 (0) | 2023.01.02 |