알고리즘

백준 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 << " ";
        }
    }
}