Baekjoon Online Judge
[문제]
N개의 정수 A[1], A[2], …, A[N]이 주어져 있을 때, 이 안에 X라는 정수가 존재하는지 알아내는 프로그램을 작성하시오.
[입력]
첫째 줄에 자연수 N(1 ≤ N ≤ 100,000)이 주어진다. 다음 줄에는 N개의 정수 A[1], A[2], …, A[N]이 주어진다. 다음 줄에는 M(1 ≤ M ≤ 100,000)이 주어진다. 다음 줄에는 M개의 수들이 주어지는데, 이 수들이 A안에 존재하는지 알아내면 된다. 모든 정수의 범위는 -2^31 보다 크거나 같고 2^31보다 작다.
[출력]
M개의 줄에 답을 출력한다. 존재하면 1을, 존재하지 않으면 0을 출력한다.
[코드]
#include <iostream>
#include <algorithm>
using namespace std;
int A[100001];
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int N, M, tmp;
cin >> N;
for (int i = 0; i < N; i++)
cin >> A[i];
sort(A, A + N);
cin >> M;
for (int i = 0; i < M; i++)
{
cin >> tmp;
if (binary_search(A, A + N, tmp))
cout << 1 << '\n';
else
cout << 0 << '\n';
}
return 0;
}
+241106 코드 추가
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> v;
bool binary_search(int len, int target)
{
int low = 0, high = len - 1;
while (low <= high)
{
int mid = (low + high) / 2;
if (target == v[mid])
return true;
if (target < v[mid])
high = mid - 1;
else if (target > v[mid])
low = mid + 1;
}
return false;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int N, M;
cin >> N;
for (int i = 0; i < N; i++)
{
int tmp;
cin >> tmp;
v.push_back(tmp);
}
sort(v.begin(), v.end());
cin >> M;
for (int i = 0; i < M; i++)
{
int tmp;
cin >> tmp;
cout << binary_search(N, tmp) << '\n';
}
return 0;
}
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> v;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int N, M;
cin >> N;
for (int i = 0; i < N; i++)
{
int tmp;
cin >> tmp;
v.push_back(tmp);
}
sort(v.begin(), v.end());
cin >> M;
for (int i = 0; i < M; i++)
{
int tmp;
cin >> tmp;
cout << binary_search(v.begin(), v.end(), tmp) << '\n';
}
return 0;
}
'Baekjoon > C++' 카테고리의 다른 글
[C++][BOJ/백준] 15649 N과 M (1) (0) | 2024.07.13 |
---|---|
[C++][BOJ/백준] 2822 점수 계산 (0) | 2024.07.12 |
[C++][BOJ/백준] 1018 체스판 다시 칠하기 (0) | 2024.07.08 |
[C++][BOJ/백준] 10867 중복 빼고 정렬하기 (0) | 2024.06.28 |
[C++][BOJ/백준] 7568 덩치 (0) | 2024.06.27 |