알고리즘&자료구조/문제

[BOJ] 5972 택배 배송 C++

Nakuri 2023. 3. 6. 18:20
728x90

개요

https://www.acmicpc.net/problem/5972

 

5972번: 택배 배송

농부 현서는 농부 찬홍이에게 택배를 배달해줘야 합니다. 그리고 지금, 갈 준비를 하고 있습니다. 평화롭게 가려면 가는 길에 만나는 모든 소들에게 맛있는 여물을 줘야 합니다. 물론 현서는

www.acmicpc.net

골드5 난이도 문제다.

풀이

가중치 그래프 문제로 기본적인 다익스트라 알고리즘 문제 유형이다.

V<=50000, E<=50000 이기 때문에 우선순위 큐를 이용한 다익스트라를 사용하면된다.(O(ElogE))

기본 다익스트라 알고리즘으로 풀면 시간 초과가 날 수 있으니 주의!(O(V^2))

코드

#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;
constexpr int LIMIT = 50002;
constexpr int MAX = 2123456789;
struct Info
{
	int node;
	int cost;
};
struct cmp 
{
	bool operator()(const Info &l, const Info &r) const 
	{
		return l.cost > r.cost;
	}
};

vector<Info> graph[LIMIT];
int dis[LIMIT];
bool fin[LIMIT];
int N, M;

void Dijkstra()
{
	priority_queue<Info, vector<Info>, cmp> pq;
	pq.push({ 1, 0 });
	fin[1] = true;
	while (!pq.empty())
	{
		auto [cur, sum] = pq.top();
		if (cur == N) break;
		fin[cur] = true;
		pq.pop();

		for (int i = 0; i < graph[cur].size(); i++)
		{
			auto next = graph[cur][i];
			if (fin[next.node]) continue;
			int nSum = sum + next.cost;
			if (dis[next.node] <= nSum) continue;
			dis[next.node] = nSum;

			pq.push({ next.node, nSum });
		}
	}
}

int main()
{
	cin.tie(0)->sync_with_stdio(0);

	cin >> N >> M;
	for (int i = 0; i <= N; i++)
		dis[i] = MAX;

	int a, b, c;
	for (int i = 0; i < M; i++)
	{
		cin >> a >> b >> c;
		graph[a].push_back({ b, c });
		graph[b].push_back({ a, c });
	}

	Dijkstra();
	
	cout << dis[N];
}

'알고리즘&자료구조 > 문제' 카테고리의 다른 글

[BOJ] 9372 상근이의 여행 C++  (0) 2023.03.28
[BOJ] 1238 파티 C++  (0) 2023.03.07
[BOJ] 1043 거짓말 C++  (1) 2023.02.24
[BOJ] 1976 여행 가자 C++  (0) 2023.02.24
[BOJ] 4195 친구 네트워크 C++  (0) 2023.02.23