Hello Ocean! ๐ŸŒผ

[๋ฐฑ์ค€/C++] 1753. ์ตœ๋‹จ๊ฒฝ๋กœ ๋ณธ๋ฌธ

Algorithm

[๋ฐฑ์ค€/C++] 1753. ์ตœ๋‹จ๊ฒฝ๋กœ

bba_dda 2021. 4. 6. 20:06
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ 

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 987654321

int min_route[20002];
int V, E, start;
vector<pair<int, int>> adj[20002];

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

	while (!pq.empty()) {
		int dist = -pq.top().first;
		int cur = pq.top().second;
		pq.pop();
		if (min_route[cur] < dist) continue; // ์ด๋ฏธ ์ตœ๋‹จ๊ฒฝ๋กœ๋ฅผ ์ฒดํฌํ•œ ๋…ธ๋“œ์ธ ๊ฒฝ์šฐ ํŒจ์Šค 

		for (int i = 0;i < adj[cur].size();i++) {
			int there = adj[cur][i].first;
			int cost = dist + adj[cur][i].second;
			if (cost < min_route[there]) {
				min_route[there] = cost;
				pq.push(make_pair(-cost, there));
			}
		}
	}

}
int main(void) {
	ios::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);

	cin >> V >> E;
	cin >> start;
	for (int i = 0;i < E;i++) {
		int a, b, cost;
		cin >> a >> b >> cost;
		adj[a].push_back(make_pair(b, cost));
	}

	for (int i = 0;i <= V;i++) {
		min_route[i] = INF;
	}
	DijkstraHeap();
	
	for (int i = 1;i <= V;i++) {
		if (min_route[i] == INF)
			cout << "INF" << "\n";
		else
			cout << min_route[i] << "\n";
	}
	return 0;
}

 

๊ฒฐ๊ณผ

* endl -> "\n" ์œผ๋กœ ๋ณ€๊ฒฝํ–ˆ๋”๋‹ˆ 800ms๊ฐ€ ์ค„์–ด๋“ค์—ˆ๋‹ค 

* ์ž…์ถœ๋ ฅ์‹œ์— ๋ฉ”์ธํ•จ์ˆ˜์— ์•„๋ž˜ ์ฝ”๋“œ๋ฅผ ๋„ฃ์ง€ ์•Š์œผ๋ฉด ์‹œ๊ฐ„์ดˆ๊ณผ๊ฐ€ ๋‚œ๋‹ค

ios::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);

๋ฐ˜์‘ํ˜•