문제
입력
출력
처음에 문제를 풀 때 거리를 구하고 그래프를 탐색하며 가중치가 있기에 다익스트라로 최장 거리를 구하는 알고리즘을 짜봤다.
int sol(int n) {
priority_queue<pair<int, int>>pq; // 최대힙
pq.push(make_pair(0, key));
while (!pq.empty()) {
int d = pq.top().first;
int p = pq.top().second;
pq.pop();
for (auto i : links[p]) {
int dc = weight[i]+d;
int pc = i;
if (dist[i] < dc) {
dist[i] = dc;
pq.push(make_pair(dc, pc));
}
}
}
int maxi = 0;
for (int i = 1; i <= n; i++) {
maxi = max(dist[i], maxi);
}
return maxi+weight[key];
}
하지만 다익스트라는 최장거리를 구할 때는 O(ElogV)가 유지되지 않는다고 한다.
그래서 DFS를 이용해보기로 했다. 각 건물에 대하여 필요한 건물들이 트리 형태를 띄고 있으므로 각 가중치를 제일 첫건물부터 끌어올릴 필요가 있다 생각했기 때문이다.
이 예제에서
정답 코드
#include <iostream>
#include <vector>
using namespace std;
vector<int>needs[1001];
int weight[1001];
bool visit[1001];
int key;
void set0() {
for (int i = 1; i <= 1000; i++) {
needs[i].clear();
visit[i] = 0;
}
}
void input(int m) {
for (int i = 0; i < m; i++) {
int a, b;
cin >> a >> b;
needs[b].push_back(a);
}
cin >> key;
}
void sol(int i) {
int maxi = 0;
for (auto p : needs[i]) {
if (!visit[p]) {
sol(p);
visit[p] = 1;
}
maxi = max(weight[p], maxi);
}
weight[i] += maxi;
}
int main() {
ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
int t;
cin >> t;
for (int p = 0; p < t; p++) {
set0();
int n, m;
cin >> n >> m;
for (int i = 1; i <= n; i++) cin >> weight[i];
input(m);
sol(key);
cout << weight[key] << '\n';
}
return 0;
}