1일1알

백준 20311번 화학 실험 C++ 본문

알고리즘

백준 20311번 화학 실험 C++

영춘권의달인 2022. 11. 5. 11:02

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

 

20311번: 화학 실험

화학 실험을 하던 윤이는 일렬로 나열해 놓은 $N$개의 시험관에서 재밌는 특징을 발견했다. 그 특징은 모든 이웃한 시험관 쌍에 대해, 두 시험관에 들어 있는 시약의 색깔이 서로 다르다는 점이

www.acmicpc.net

 

우선순위 큐 사용해서 시뮬레이션

 

#include <iostream>
#include <string>
#include <vector>
#include <math.h>
#include <algorithm>
#include <utility>
#include <stack>
#include <queue>
#include <math.h>
#include <set>
#include <map>
#include <list>
#include <unordered_map>
#include <unordered_set>
#include <iomanip>
#include <limits.h>

using namespace std;
using int64 = long long;

int n, k;

struct Info {
    int num;
    int cnt;

    bool operator<(const Info& other) const {
        return cnt < other.cnt;
    }
    bool operator>(const Info& other) const {
        return cnt > other.cnt;
    }
};

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    
    cin >> n >> k;
    priority_queue<Info, vector<Info>> pq;
    for (int i = 1; i <= k; i++) {
        int cnt;
        cin >> cnt;
        pq.push({ i,cnt });
    }
    vector<int> ans;
    while (!pq.empty()) {
        auto curr = pq.top();
        pq.pop();
        if (ans.empty()) {
            ans.push_back(curr.num);
            curr.cnt -= 1;
        }
        else {
            if (ans.back() == curr.num) {
                if (pq.empty()) {
                    ans.clear();
                    break;
                }
                auto curr2 = pq.top();
                pq.pop();
                ans.push_back(curr2.num);
                curr2.cnt -= 1;
                if (curr2.cnt > 0) {
                    pq.push({ curr2.num,curr2.cnt});
                }
            }
            else {
                ans.push_back(curr.num);
                curr.cnt -= 1;
            }
        }
        if (curr.cnt > 0) {
            pq.push({ curr.num,curr.cnt });
        }
    }
    if (ans.empty()) cout << -1;
    else {
        for (auto a : ans) {
            cout << a << " ";
        }
    }
}

'알고리즘' 카테고리의 다른 글

백준 14241번 슬라임 합치기 C++  (0) 2022.11.09
백준 11060번 점프 점프 C++  (0) 2022.11.07
백준 23351번 물 주기 C++  (0) 2022.11.04
백준 1245번 농장 관리 C++  (0) 2022.11.03
백준 17178번 줄서기 C++  (0) 2022.11.02