코딩테스트/그래프|트리
[위상정렬(BFS+DP)] (CHECK) 백준 1005 ACM Craft C++
유(YOO)
2023. 8. 31. 15:03
https://www.acmicpc.net/problem/1005
최대 중 최소X, 전제조건
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
int t;
cin >> t;
int n, k, w;
int d[1001];
for(int i=0; i<t; i++) {
cin >> n >> k;
for(int i=1; i<=n; i++) cin >> d[i];
vector<int> graph[1001];
vector<int> indegree(n+1, 0);
for(int i=0; i<k; i++) {
int a, b;
cin >> a >> b;
graph[a].push_back(b);
indegree[b]++;
}
cin >> w;
queue<int> q;
vector<int> dist(n+1, 0);
for(int i=1; i<=n; i++) {
if (indegree[i] == 0) {
q.push(i);
dist[i] = d[i];
}
}
while(!pq.empty()) {
int p = q.front();
q.pop();
for(auto v : graph[p]) {
dist[v] = max(dist[v], dist[p] + d[v]);
indegree[v]--;
if (indegree[v] == 0) pq.push(v);
}
}
cout << dist[w] << "\n";
}
return 0;
}