Notice
Recent Posts
Recent Comments
Link
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
Archives
Today
Total
관리 메뉴

알고리즘 공부방

백준 16566 카드 게임(C++) 본문

알고리즘

백준 16566 카드 게임(C++)

head89 2022. 12. 28. 02:22

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

 

16566번: 카드 게임

첫째 줄에 세 개의 자연수 N, M, K가 주어진다. (1 ≤ M ≤ N ≤ 4,000,000, 1 ≤ K ≤ min(M, 10,000)) 다음 줄에 카드의 번호를 나타내는 M개의 자연수가 주어진다. 각각의 수들은 1 이상이고 N 이하이며 서로

www.acmicpc.net

 

문제 유형: 이분탐색, Union-Find

 

 

문제 설명

먼저 설명하기전에 c++ 입출력 억까를 당했다..

문제를 설명하면 먼저 입력에 주어진 배열을 저장한다.

그리고 k개의 자연수가 주어졌을 때, 이분탐색의 응용중 하나인 Upper Bound를 사용하여, k다음으로 큰 수를 배열에서 찾고, 출력해준다.

그리고 출력한 수는 다시 쓸 수 없으므로 똑같은 수가 주어졌을 때 k다음으로 큰수 다음으로 큰수를 출력해줘야한다.

그러기 위해선, Union-Find를 사용하여, 그 수를 가르키게 만드는 것으로 구현했다..

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int parent[4000001];
int n,m,k;
vector<int> arr;
int Find(int x){
    if(parent[x] ==x) return parent[x];

    return parent[x] = Find(parent[x]);
}

void Union(int x, int y){
    x = Find(x);
    y = Find(y);
    if(x!=y){
        if(x>y) parent[y] = x;
        else parent[x] = y;
    }
}

int main() {
    ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
    cin >> n >> m >> k;
    for(int i = 0;i<m;i++){
        int num;
        cin >> num;
        arr.push_back(num);
        parent[i] = i;
    }
    sort(arr.begin(), arr.end());
    int temp;
    for(int i = 0;i<k;i++){
        cin >> temp;
        int index = upper_bound(arr.begin(), arr.end(),temp) - arr.begin();
        int p = Find(index);
        cout << arr[p] << endl;
        Union(p, p + 1);
    }
    return 0;
}