본문 바로가기
문제/백준

c++ 백준_1753_"최단경로"

by 나 진짜 못차마 2023. 6. 16.
728x90

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

 

우선순위큐를 사용한 다익스트라 문제이다.

예전에 못풀어서 놔둔 거

이제 우선순위 큐 다익스트라가 익숙해져서

다시 해보았다.

근돼!

BAAAM

요것의 문제는

endl ; 이 아닌

"\n";

를 사용해야 했다.

holymoly

출력이 최대 20,000개 정도 되니 요런 것을 신경을 써줘야됐다

쟁신 차려 쟁신

 

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

#define INF 1000000000

int dist[20001];
vector<pair<int, int>> node[20001];

struct comp {
	bool operator()(pair<int, int> a, pair<int, int> b) {
		return a.second > b.second;
	}
};

void shortest_path(int N, int start) {

	priority_queue < pair<int, int>, vector<pair<int, int>>, comp> pq;

	for (int i = 1; i <= N; i++) {
		dist[i] = INF;
	}

	dist[start] = 0;

	pq.push(make_pair(start, 0));

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

		if (dist[u] < weight)
			continue;

		for (int i = 0; i < node[u].size(); i++) {

			int next = node[u][i].first;
			int D = node[u][i].second;

			if (weight + D < dist[next]) {
				dist[next] = weight + D;
				pq.push(make_pair(next, dist[next]));
			}
		}
	}
}

int main(void) {
	int V, E, K;

	cin >> V >> E;
	cin >> K;


	
	int u, v, weight;
	for (int i = 0; i < E; i++) {
		cin >> u >> v >> weight;

		node[u].push_back(make_pair(v, weight));
	}


	shortest_path(V, K);

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


}

728x90

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

c++ 백준_23562_"ㄷ 만들기"  (0) 2023.06.16
c++ 백준_2252_"줄 세우기"  (0) 2023.06.16
c++ 백준_1600_"말이 되고픈 원숭이"  (0) 2023.06.15
c++ 백준_1405_"미친 로봇"  (0) 2023.06.15
c++ 백준_1715_"카드 정렬하기"  (0) 2023.06.15