1753번: 최단경로
첫째 줄에 정점의 개수 V와 간선의 개수 E가 주어진다. (1≤V≤20,000, 1≤E≤300,000) 모든 정점에는 1부터 V까지 번호가 매겨져 있다고 가정한다. 둘째 줄에는 시작 정점의 번호 K(1≤K≤V)가 주어진다.
www.acmicpc.net
한 정점에서 다른 모든 정점까지의 최단 경로를 구하는 다익스트라 알고리즘을 이용하면 쉽게 풀 수 있는 문제였다.
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
const int INF = 987654321;
int V, E;
vector<pair<int, int>> adj[20001];
vector<int> dijkstra(int start)
{
vector<int> dist(V+1, INF);
dist[start] = 0;
priority_queue<pair<int, int>> pq;
pq.push({ 0, start });
while (!pq.empty())
{
int here = pq.top().second;
int cost = -pq.top().first;
pq.pop();
if (dist[here] < cost) continue;
for (int i = 0; i < 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(void)
{
cin.tie(0);
ios_base::sync_with_stdio(0);
cin >> V >> E;
int start;
cin >> start;
for (int i = 0; i < E; i++)
{
int u, v, w;
cin >> u >> v >> w;
adj[u].push_back({ v,w });
}
vector<int> result = dijkstra(start);
for (int i = 1; i <= V; i++)
{
if (result[i] == INF)
cout << "INF" << '\n';
else
cout << result[i] << '\n';
}
return 0;
}
알고리즘 200일 프로젝트 - 163 day
'알고리즘 > BOJ' 카테고리의 다른 글
백준 2252번: 줄 세우기 (0) | 2020.09.19 |
---|---|
백준 13460번: 구슬 탈출 2 (0) | 2020.09.19 |
백준 2667번: 단지번호붙이기 (0) | 2020.09.19 |
백준 2178번: 미로 탐색 (0) | 2020.09.19 |
백준 1786번: 찾기 (0) | 2020.08.24 |