[BOJ] 1516๋ฒ | ๊ฒ์ ๊ฐ๋ฐ (C++)
2023. 12. 19. 15:06ใCoding Test/BOJ
๐๋ฌธ์ ๋ณด๋ฌ๊ฐ๊ธฐ
๐ง๐ปํ์ด ๊ณผ์
๋์ ๊ณํ๋ฒ(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
๋ฐ์ํ
'Coding Test > BOJ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[BOJ] 11779๋ฒ | ์ต์๋น์ฉ ๊ตฌํ๊ธฐ 2 (C++) (1) | 2023.12.20 |
---|---|
[BOJ] 2623๋ฒ | ์์ ํ๋ก๊ทธ๋จ (C++) (1) | 2023.12.19 |
[BOJ] 1766๋ฒ | ๋ฌธ์ ์ง (C++) (0) | 2023.12.19 |
[BOJ] 1074๋ฒ | Z (C++) (0) | 2023.12.18 |
[BOJ] 1916๋ฒ | ์ต์๋น์ฉ ๊ตฌํ๊ธฐ (C++) (0) | 2023.12.13 |