[ ALGORITHM ]/[ 백 준 ]

[BAEKJOON] 1753번 : 최단경로

HiStar__ 2020. 9. 7. 21:20

문 제

 

 

소 스  코 드

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

constexpr int INF { 0x7fff'0000 };

struct Edge {
	int mV;
	int mWeight;	

	bool operator <(const Edge& other) const {
		return mWeight > other.mWeight;
	}

};

class Graph {
public:
	Graph() = delete;
	Graph(const int& v){ 
		mGraph.resize(v + 1);
		mDist.resize(v + 1);
	}

	void AddEdge(const int& u, const int v, const int w) {
		mGraph[u].emplace_back(Edge{ v, w });
	}

	void Display() {
		for (int i = 1; i < mGraph.size(); ++i) {
			std::cout << i << " : ";
			for (const auto& a : mGraph[i]) {
				std::cout << a.mV << " : " << a.mWeight << "  ";
			}
			std::cout << '\n';
		}
	}

	void SearchShortestPath(const int& start) {
		if (start < 0 || start > mDist.size()) return;

		for (int i = 1; i < mDist.size(); ++i) mDist[i] = INF;
		mDist[start] = 0;
		
		// Queue Clear
		while (!pQue.empty()) pQue.pop();

		for (int i = 1; i < mDist.size(); ++i) pQue.push(Edge{ i, mDist[i] });

		while (!pQue.empty()) {
			Edge temp{ pQue.top() };
			pQue.pop();

			if (mDist[temp.mV] < temp.mWeight) continue;

			for (const auto& a : mGraph[temp.mV]) {
				int plus{ mDist[temp.mV] + a.mWeight };
				if (mDist[a.mV] > plus) {
					mDist[a.mV] = plus;
					pQue.push(Edge{ a.mV, mDist[a.mV] });
				}
			}
		}

		for (int i = 1; i < mDist.size(); ++i) {
			if (INF == mDist[i]) std::cout << "INF \n";
			else				 std::cout << mDist[i] << '\n';
		}


	}


private:
	std::vector<std::vector<Edge>> mGraph; // weight, pos
	std::priority_queue<Edge> pQue;
	std::vector<int> mDist;

};

int main() {
	std::ios_base::sync_with_stdio(false);
	std::cin.tie(NULL);
	std::cout.tie(NULL);

	int V, E, K;

	std::cin >> V >> E >> K;

	Graph graph(V);

	int u, v, w;
	for (int i = 0; i < E; ++i) {
		std::cin >> u >> v >> w;
		graph.AddEdge(u, v, w);
	}

	graph.SearchShortestPath(K);


	return 0;
}

 

풀 이

 

더보기

STL의 Priority Queue( 우선순위 큐 ) 를 사용하였습니다.

 

점과 점 사이의 선은 단방향으로 이루어져있다.

 

우선순위 큐는 가중치 w가 적은 순서대로 하였고,

현재, 거리의 누적과 비교 하였을 경우에 w가 더 클 경우 

비교를 하여 누적거리를 갱신하는 과정을 거쳤다.

 

주의) 이 문제의 경우, 간선의 최대 INF가 int의 최댓값인 0x7ffff'ffff일 경우.

만약, 맨 먼저 들여 놓았던 5, INF 기본값에서 변경이 없기 때문에, 우선순위 큐에 저 값을 판단할 경우,

이전에 dist[5] = INF 이고, 5에서 1인 1의 값을 더하여 값이 이상해지기 때문에 유의하여 구현을 하여야 한다. 

 

 

출 력 값

 

 

문 제  출 처

문제 링크 : 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