PS/BOJ
[알고리즘] 백준 12384번: 주간 미팅 (C++)
도비(Doby)
2021. 12. 9. 21:18
https://www.acmicpc.net/problem/12834
12834번: 주간 미팅
첫째 줄에 KIST 기사단 팀원의 수 N, 장소의 수 V, 도로의 수 E가 주어진다. (N ≤ 100, V ≤ 1000, E ≤ 10000) 둘째 줄에 KIST의 위치 A와 씨알푸드의 위치 B가 주어진다. (1 ≤ A, B ≤ V) 셋째 줄에 팀원 N명의
www.acmicpc.net
간단한 다익스트라 문제다.
갈 수 없는 길이 나올 땐 -1 처리를 해주고, 모든 최단 경로를 더한 값을 출력하면 된다.
#include <iostream>
#include <queue>
#include <vector>
#include <utility>
#define MAX 1000 + 1
#define INF 987654321
#define pii pair<int, int>
using namespace std;
vector<pii> graph[MAX];
int n, v, e;
struct cmp {
bool operator()(pii& a, pii& b) {
return a.second > b.second;
}
};
vector<int> dijkstra(int node) {
vector<int> dist(v + 1, INF);
dist[node] = 0;
priority_queue<pii, vector<pii>, cmp> pq;
pq.push({ node, 0 });
while (!pq.empty()) {
int now = pq.top().first;
int cost = pq.top().second;
pq.pop();
if (dist[now] < cost) {
continue;
}
for (int i = 0; i < graph[now].size(); i++) {
int next = graph[now][i].first;
int nextCost = graph[now][i].second;
if (cost + nextCost < dist[next]) {
dist[next] = cost + nextCost;
pq.push({ next, dist[next] });
}
}
}
return dist;
}
int main() {
cin >> n >> v >> e;
int a, b;
cin >> a >> b;
vector<int> team;
for (int i = 1, value; i <= n; i++) {
cin >> value;
team.push_back(value);
}
for (int i = 0; i < e; i++) {
int start, end, w;
cin >> start >> end >> w;
graph[start].push_back({ end, w });
graph[end].push_back({ start, w });
}
int sum = 0;
for (int i = 0; i < team.size(); i++) {
vector<int> temp = dijkstra(team[i]);
if (temp[a] == INF) sum += -1;
else sum += temp[a];
if (temp[b] == INF) sum += -1;
else sum += temp[b];
}
cout << sum;
return 0;
}