IT's 2 EG
백준 1753번 - 최단경로 본문
1753번: 최단경로
첫째 줄에 정점의 개수 V와 간선의 개수 E가 주어진다. (1≤V≤20,000, 1≤E≤300,000) 모든 정점에는 1부터 V까지 번호가 매겨져 있다고 가정한다. 둘째 줄에는 시작 정점의 번호 K(1≤K≤V)가 주어진다.
www.acmicpc.net
더보기
#include <iostream>
#include <cstdio>
#include <queue>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
typedef pair<int, int> node;
int V, E; //V: 정점의 개수, E: 간선의 개수
int sp;
bool visited[20001];
int dist[20001];
vector<node> graph[20001];
priority_queue<node, vector<node>, greater<node> >PQ;
void Dijkstra(int p)
{
PQ.push(node(dist[p], p));
while (!PQ.empty())
{
int curr = PQ.top().second;
PQ.pop();
for (node &np : graph[curr])
{
int pos = np.first;
int dis = np.second;
if (dist[pos] > dist[curr] + dis)
{
dist[pos] = dist[curr] + dis;
PQ.push(node(dist[pos], pos));
}
}
}
}
int main()
{
scanf("%d %d %d", &V, &E, &sp);
for (int i = 0; i < E; i++)
{
int u, v, w;
scanf("%d %d %d", &u, &v, &w);
graph[u].push_back(make_pair(v, w));
}
for (int i = 1; i <= V; i++)
dist[i] = 2e9;
dist[sp] = 0;
Dijkstra(sp);
for (int i = 1; i <= V; i++)
{
if (dist[i] == 2e9)
printf("INF\n");
else
printf("%d\n", dist[i]);
}
return 0;
}
'알고리즘 > 백준 문제풀이' 카테고리의 다른 글
백준 1697번 - 숨바꼭질 (0) | 2020.09.07 |
---|---|
백준 1260번 - DFS와 BFS (0) | 2020.09.04 |
백준 2178번 - 미로 탐색 (0) | 2020.09.04 |
Comments