๋ณธ๋ฌธ์œผ๋กœ ๋ฐ”๋กœ๊ฐ€๊ธฐ
728x90

 

๐Ÿ”—๋ฌธ์ œ ๋ณด๋Ÿฌ๊ฐ€๊ธฐ
 

1516๋ฒˆ: ๊ฒŒ์ž„ ๊ฐœ๋ฐœ

์ฒซ์งธ ์ค„์— ๊ฑด๋ฌผ์˜ ์ข…๋ฅ˜ ์ˆ˜ N(1 ≤ N ≤ 500)์ด ์ฃผ์–ด์ง„๋‹ค. ๋‹ค์Œ N๊ฐœ์˜ ์ค„์—๋Š” ๊ฐ ๊ฑด๋ฌผ์„ ์ง“๋Š”๋ฐ ๊ฑธ๋ฆฌ๋Š” ์‹œ๊ฐ„๊ณผ ๊ทธ ๊ฑด๋ฌผ์„ ์ง“๊ธฐ ์œ„ํ•ด ๋จผ์ € ์ง€์–ด์ ธ์•ผ ํ•˜๋Š” ๊ฑด๋ฌผ๋“ค์˜ ๋ฒˆํ˜ธ๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๊ฑด๋ฌผ์˜ ๋ฒˆํ˜ธ๋Š” 1๋ถ€

www.acmicpc.net

 

๐Ÿง‘‍๐Ÿ’ปํ’€์ด ๊ณผ์ •

 

๋™์  ๊ณ„ํš๋ฒ•(Dynamic Programming)๊ณผ ์œ„์ƒ ์ •๋ ฌ(Topological Sort)๋ฅผ ์‚ฌ์šฉํ•ด ํ’€ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

์ง„์ž… ์ฐจ์ˆ˜๊ฐ€ 0์ธ ๋…ธ๋“œ(v)์—์„œ ๋‹ค๋ฅธ ์ธ์ ‘ ๋…ธ๋“œ(other)๋กœ ํ–ฅํ•  ๋•Œ, ๋‹ค์Œ ๋กœ์ง๋งŒ ์ถ”๊ฐ€ํ•ด์ฃผ๋ฉด ๋ฉ๋‹ˆ๋‹ค.

*constructionTimes[i] : i ๋ฒˆ์งธ ๊ฑด๋ฌผ์˜ ๊ฑด์„ค ์‹œ๊ฐ„

*answers[i] : ๋จผ์ € ์ง€์–ด์•ผ ํ•˜๋Š” ๊ฑด๋ฌผ์„ ์ง“๊ณ  ๋‚œ ํ›„, i ๋ฒˆ์งธ ๊ฑด๋ฌผ๊นŒ์ง€ ์ง“๋Š” ๋ฐ ๊ฑธ๋ฆฌ๋Š” ์ตœ์†Œ ์‹œ๊ฐ„

 

answers[other] = max(answers[other],  answers[v] + constructionTimes[other])

 

 

โœ๏ธ์†Œ์Šค ์ฝ”๋“œ ๋ฐ ๊ฒฐ๊ณผ

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

using namespace std;
#define FAST_IO ios::sync_with_stdio(false); cout.tie(NULL); cin.tie(NULL);

vector<vector<int>> Graph;
vector<int> ConstructionTimes;
vector<int> InDegrees;

vector<int> Solution(int N) {
    vector<int> answers(N + 1);
    queue<int> buildings;

    for (int i = 1; i <= N; i++) {
        if (InDegrees[i] == 0) {
            buildings.push(i);
            answers[i] = ConstructionTimes[i];
        }
    }

    for (int i = 1; i <= N; i++) {
        int v = buildings.front();
        buildings.pop();

        for (const auto& other : Graph[v]) {
            answers[other] = max(answers[other], answers[v] + ConstructionTimes[other]);

            if (--InDegrees[other] == 0)
                buildings.push(other);
        }
    }

    return answers;
}

int main() {
    FAST_IO
    int N, constructionTime, preBuilding;
    cin >> N;

    Graph.resize(N + 1);
    ConstructionTimes.resize(N + 1);
    InDegrees.resize(N + 1);

    for (int i = 1; i <= N; i++) {
        cin >> constructionTime;
        ConstructionTimes[i] = constructionTime;

        while (true) {
            cin >> preBuilding;
            
            if (preBuilding == -1)
                break;
            Graph[preBuilding].emplace_back(i);
            InDegrees[i]++;
        }
    }

    vector<int> answers = Solution(N);
    for (int i = 1; i <= N; i++)
        cout << answers[i] << "\n";

    return 0;
}

 

 

728x90
๋ฐ˜์‘ํ˜•