Hello Ocean! ๐ŸŒผ

[๋ฐฑ์ค€/C++] 1916. ์ตœ์†Œ๋น„์šฉ ๊ตฌํ•˜๊ธฐ ๋ณธ๋ฌธ

Algorithm

[๋ฐฑ์ค€/C++] 1916. ์ตœ์†Œ๋น„์šฉ ๊ตฌํ•˜๊ธฐ

bba_dda 2021. 4. 14. 12:42
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ 

www.acmicpc.net/problem/1916

 

1916๋ฒˆ: ์ตœ์†Œ๋น„์šฉ ๊ตฌํ•˜๊ธฐ

์ฒซ์งธ ์ค„์— ๋„์‹œ์˜ ๊ฐœ์ˆ˜ N(1 ≤ N ≤ 1,000)์ด ์ฃผ์–ด์ง€๊ณ  ๋‘˜์งธ ์ค„์—๋Š” ๋ฒ„์Šค์˜ ๊ฐœ์ˆ˜ M(1 ≤ M ≤ 100,000)์ด ์ฃผ์–ด์ง„๋‹ค. ๊ทธ๋ฆฌ๊ณ  ์…‹์งธ ์ค„๋ถ€ํ„ฐ M+2์ค„๊นŒ์ง€ ๋‹ค์Œ๊ณผ ๊ฐ™์€ ๋ฒ„์Šค์˜ ์ •๋ณด๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๋จผ์ € ์ฒ˜์Œ์—๋Š” ๊ทธ

www.acmicpc.net

ํ’€์ด

๋‹ค์ต์ŠคํŠธ๋ผ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์ด์šฉํ•ด์„œ ํ’€์—ˆ๋‹ค. 

์‹œ๊ฐ„ ๋ณต์žก๋„๋ฅผ ๋‚ฎ์ถ”๊ธฐ ์œ„ํ•ด ํž™์„ ์ด์šฉํ•ด ๊ตฌํ˜„ํ–ˆ๋‹ค. 

์‹œ๊ฐ„๋ณต์žก๋„ : ๋…ธ๋“œ๊ฐ€ V,๊ฐ„์„ ์ด E๊ฐœ ์ผ ๋•Œ, O(E*logV)

 

๋ฐฑ์ง€ ์ƒํƒœ์—์„œ ๊ตฌํ˜„ํ•˜๋ ค๋‹ˆ ์ƒ๊ฐ์ด ๋‚˜์ง€ ์•Š์•„์„œ, ์ €๋ฒˆ์— ๊ตฌํ˜„ํ•ด๋’€๋˜ ์ฝ”๋“œ๋ฅผ ์ถฉ๋ถ„ํžˆ ์ˆ™์ง€ํ•œ ํ›„์— ๊ตฌํ˜„ํ•ด๋ณด์•˜๋‹ค.

์ฝ”๋“œ

#include <iostream>
#include <vector>
#include <queue>

using namespace std;

#define INF 987654321

vector<pair<int, int>> adjs[1001];
int min_dist[1001];

void Dijkstra(int start) {
	priority_queue<pair<int, int>> pq;
	pq.push(make_pair(0, start));
	min_dist[start] = 0; //////

	while (!pq.empty()) {
		int cost = -pq.top().first;
		int cur = pq.top().second;
		pq.pop();/////
		if (min_dist[cur] < cost) continue;

		for (int i = 0;i < adjs[cur].size();i++) {
			int there = adjs[cur][i].first;
			int new_cost = cost + adjs[cur][i].second;
			if (min_dist[there] > new_cost) {
				min_dist[there] = new_cost;
				pq.push(make_pair(-new_cost, there));
			}
		}
	}
}
int main(void) {
	// ์ž…์ถœ๋ ฅ ์‹œ๊ฐ„ ๋‹จ์ถ•์šฉ
	ios::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);

	int n, m, a, b;
	cin >> n >> m;
	for (int i = 0;i < m;i++) {
		int start, end, cost;
		cin >> start >> end >> cost;
		adjs[start].push_back(make_pair(end, cost));
	}
	cin >> a >> b;
	fill(&min_dist[0], &min_dist[1002], INF);
	Dijkstra(a);
	cout << min_dist[b] << endl;
	return 0;
}

๊ฒฐ๊ณผ

 

๋ฐ˜์‘ํ˜•