λ°±μ€€/C++

[λ°±μ€€/C++] 1005번 ACM Craft

yulee_to 2022. 7. 16. 17:06

λ°±μ€€
λ°±μ€€


πŸ€”λ¬Έμ œ 이해

선행관계가 μžˆλŠ” μž‘μ—…μ€ μ„ ν–‰ μž‘μ—…μ„ λͺ¨λ‘ λ§ˆμ³€μ„ λ•Œ μˆ˜ν–‰λ  수 μžˆμœΌλ―€λ‘œ μˆœμ„œλŒ€λ‘œ μž‘μ—…ν•˜λ‹€κ°€ νŠΉμ • 건물의 건섀이 μ™„λ£Œν•  λ•ŒκΉŒμ§€ κ±Έλ¦¬λŠ” μ΅œμ†Œ μ‹œκ°„μ„ κ΅¬ν•˜λ©΄ λœλ‹€.


πŸ’‘μ²«λ²ˆμ§Έ 아이디어

λ™μ‹œμ— μž‘μ—…λ  수 μžˆλŠ” μž‘μ—…λ“€ 쀑 μ‹œκ°„μ΄ 적게 κ±Έλ¦¬λŠ” μž‘μ—…μ΄ λ¨Όμ € λ‹€ μˆ˜ν–‰λ˜μ–΄μ•Ό ν•˜λ―€λ‘œ priority queueλ₯Ό μ‚¬μš©ν•˜λ©΄ λœλ‹€.

 

πŸ”₯풀이πŸ”₯

 

pqμ—μ„œ κ°€μž₯ μ‹œκ°„μ΄ 적게 κ±Έλ¦¬λŠ” μž‘μ—…μ„ λ¨Όμ € μˆ˜ν–‰ν•˜κ³  κ·Έ μž‘μ—… λ‹€μŒμ— μˆ˜ν–‰λ  수 μžˆλŠ” μž‘μ—…μ˜ in_degreeλ₯Ό ν•˜λ‚˜ 쀄여쀀닀.

in_degreeλ₯Ό μ€„μ˜€μ„ λ•Œ κ·Έ 값이 0이라면 λ‹€μŒμ— λ°”λ‘œ μˆ˜ν–‰ν•  수 μžˆμœΌλ―€λ‘œ pq에 ν˜„μž¬μ™€ λ‹€μŒ μž‘μ—…μ˜ μˆ˜ν–‰μ‹œκ°„μ„ λ”ν•œ κ°’κ³Ό λ‹€μŒ 정점을 λ„£μ–΄μ€€λ‹€. 

μœ„ 과정을 λ°˜λ³΅ν•˜λ‹€κ°€ 찾고자 ν•˜λŠ” μž‘μ—…μ΄ pop될 λ•Œ κ·Έ μž‘μ—…μ˜ μˆ˜ν–‰μ‹œκ°„μ„ 좜λ ₯ν•΄μ£Όλ©΄ λœλ‹€.


μ•„λž˜λŠ” μ œμΆœν•œ μ½”λ“œμ΄λ‹€.

#include <iostream>
#include <vector>
#include <queue>

using namespace std;

int main() {
    cin.tie(nullptr);
    cout.tie(nullptr);
    ios::sync_with_stdio(false);

    int t;
    cin >> t;
    int n, k, x, y, w;

    while (t--) {
        cin >> n >> k;

        int time[1002] = {0,};
        int in_degree[1002] = {0,};
        for (int i = 1; i <= n; i++) {
            cin >> time[i];
        }

        vector<vector<int>> v;
        v.resize(n+1);
        for (int i = 0; i < k; i++) {
            cin >> x >> y;
            v[x].push_back(y);
            in_degree[y]++;
        }
        cin >> w;

        priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
        for (int i = 1; i <= n; i++) {
            if (!in_degree[i]) {
                pq.push({time[i], i});
            }
        }

        while (!pq.empty()) {
            int end_time = pq.top().first;
            int num = pq.top().second;
            pq.pop();
            if (num == w) {
                cout << end_time << "\n";
                break;
            }
            for (int next: v[num]) {
                in_degree[next]--;
                if (!in_degree[next]) {
                    pq.push({end_time + time[next], next});
                }
            }
        }
    }
}

 

728x90