티스토리 뷰

백준

백준 소스코드 [C++] 14284 간선 이어가기 2

Hani_Levenshtein 2020. 11. 23. 22:18

www.acmicpc.net/problem/14284

 

14284번: 간선 이어가기 2

정점 n개, 0개의 간선으로 이루어진 무방향 그래프가 주어진다. 그리고 m개의 가중치 간선의 정보가 있는 간선리스트가 주어진다. 간선리스트에 있는 간선 하나씩 그래프에 추가해 나갈 것이다.

www.acmicpc.net

백준 소스코드 [C++] 14284 간선 이어가기 2

#include <iostream>
#include <algorithm>
#include <queue>
#include <string.h>
#include <limits.h>
#include <vector>
#include <math.h>
#include <stack>
#include <bitset>
#include <string>
typedef long long ll;
using namespace std;
int n, m,u,v,w;
vector<pair<int, int>> arr[5001];
vector<int> dijkstra(int a) {
	priority_queue<pair<int, int>> pq;
	vector<int>res(n,INT_MAX);
	res[a] = 0;
	pq.push({ 0,a });
	while (pq.empty() != true) {
		int cost = -pq.top().first;
		int here = pq.top().second;
		pq.pop();
		for (int i = 0;i < arr[here].size();i++) {
			int there = arr[here][i].first;
			int nextcost = cost + arr[here][i].second;
			if (res[there] > nextcost) {
				res[there] = nextcost;
				pq.push({ -nextcost,there });
			}

		}
	}
	return res;
}

int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cin >> n >> m;
	
	for (int i = 0;i < m;i++) {
		cin >> u >> v >> w;
		arr[u - 1].push_back({ v - 1,w });
		arr[v - 1].push_back({ u - 1,w });
	}
	int a, b;
	cin >> a >> b;
	cout << dijkstra(a-1)[b-1];

	return 0;
}
댓글