Creative Code

[1753번]최단경로 본문

백준 문제풀이

[1753번]최단경로

빛하루 2023. 9. 24. 17:35

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

#include<iostream>
#include<vector>
#include<queue>
using namespace std;

#define INF 1000000000 // 10억

int V, E, K;
int u, v, w;
int weight, node, next_weight, next_node;
int ans[20001];
vector<pair<int, int>> vec[20001];
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;

int main(){
    cin.tie(0);
    cout.tie(0);
    ios_base::sync_with_stdio(false);
	cin >> V >> E >> K;

	for (int i = 1; i <= V; i++) ans[i] = INF;

	for (int i = 0; i < E; i++)
	{
		cin >> u >> v >> w;
		vec[u].push_back(pair<int, int>(v, w));
	}

	ans[K] = 0;
	pq.push(make_pair(0, K)); // 가중치 크기순서대로 넣기위해 (가중치,노드)으로 push

	while (!pq.empty())
	{
		weight = pq.top().first;
		node = pq.top().second;
		pq.pop();

		for (int i = 0; i < vec[node].size(); i++)
		{
			next_node = vec[node][i].first;
			next_weight = weight + vec[node][i].second;
			if (ans[next_node] > next_weight)
			{
				ans[next_node] = next_weight;
				pq.push(make_pair(next_weight, next_node));
			}
		}
	}

	for (int i = 1; i <= V; i++)
	{
		if (ans[i] == INF) cout << "INF" << '\n';
		else cout << ans[i] << '\n';
	}
}

'백준 문제풀이' 카테고리의 다른 글

[7662번]이중 우선순위 큐  (0) 2023.09.24
[1806번]부분합  (0) 2023.09.24
[1043번]거짓말  (0) 2023.09.24
[16928번]뱀과 사다리 게임  (0) 2023.09.24
[12856번]평범한 배낭  (0) 2023.09.24