본문 바로가기
PS(Problem Solving)/백준_BOJ

[백준] 20495번 - 수열과 헌팅 (C++) 문제 및 풀이

by 초코칩프라푸치노 2022. 2. 23.

문제) 백준 - 이분 탐색 - 수열과 헌팅

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

 

20495번: 수열과 헌팅

예제에서, 수열의 수들을 차례로 x1, x2, x3이라 하자. -10 ≤ x1 ≤ 30, 25 ≤ x2 ≤ 55, 55 ≤ x3 ≤ 85이다. 만약 (x1, x2, x3) = (28, 25, 70)이라면, x2가 첫번째, x1이 두번째, x3이 세 번째 수가 된다. 또, (x1, x2

www.acmicpc.net

 

최대, 최소를 배열과 벡터에 저장합니다. 배열에 있는 수는 탐색할 숫자이며 벡터에 있는 수는 정렬을 하여 탐색할 범위입니다. 최솟값을 최댓값이 정렬된 벡터의 lower_bound, 최댓값을 최솟값이 정렬된 벡터의 upper_bound를 통해 인덱스를 구합니다.

 

C++ 소스코드)

#include <bits/stdc++.h>
#define endl "\n"
#define ll long long
#define INF 987654321
#define MAX 500001
using namespace std;
int N;
int small[MAX], big[MAX];
vector<int> l, r;
signed main(){
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
cin >> N;
for(int i = 0; i < N; ++i){
int a, b; cin >> a >> b;
small[i] = a - b;
big[i] = a + b;
l.push_back(a - b);
r.push_back(a + b);
}
sort(l.begin(), l.end());
sort(r.begin(), r.end());
for(int i = 0; i < N; ++i)
cout << lower_bound(r.begin(), r.end(), small[i]) - r.begin() + 1 << " " << upper_bound(l.begin(), l.end(), big[i]) - l.begin() << endl;
return 0;
}
view raw 20495.cpp hosted with ❤ by GitHub

반응형

댓글