백준
백준 소스코드 [C++] 1753 최단경로
Hani_Levenshtein
2020. 8. 26. 14:44
https://www.acmicpc.net/problem/1753
1753번: 최단경로
첫째 줄에 정점의 개수 V와 간선의 개수 E가 주어진다. (1≤V≤20,000, 1≤E≤300,000) 모든 정점에는 1부터 V까지 번호가 매겨져 있다고 가정한다. 둘째 줄에는 시작 정점의 번호 K(1≤K≤V)가 주어진다.
www.acmicpc.net
백준 소스코드 [C++] 1753 최단경로
#include <iostream>
#include <algorithm>
#include <queue>
#include <string.h>
#include <limits.h>
using namespace std;
int v, e, start, s, d, weight;
vector <pair<int, int>> adj[20000];
vector<int> dijkstra(int src) {
priority_queue <pair<int, int> > pq;
vector<int> dist(v, INT_MAX);
dist[src] = 0;
pq.push({ 0,src });
while (pq.empty() != true) {
int cost = -pq.top().first;
int here = pq.top().second;
pq.pop();
if (dist[here] < cost) continue;
for (int i = 0;i < (int)adj[here].size();i++) {
int there = adj[here][i].first;
int nextdist = cost + adj[here][i].second;
if (dist[there] > nextdist) {
dist[there] = nextdist;
pq.push({ -nextdist,there });
}
}
}
return dist;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin >> v >> e;
cin >> start;
for (int i = 0;i < e;i++) {
cin >> s >> d >> weight;
adj[s-1].push_back(make_pair(d-1, weight));
}
vector<int> res=dijkstra(start-1);
for(int i=0;i<res.size();i++)
if (res[i]==INT_MAX) cout<<"INF"<<'\n';
else cout << res[i] << '\n';
return 0;
}