알고스팟 문제 링크: https://algospot.com/judge/problem/read/ROUTING
algospot.com :: ROUTING
신호 라우팅 문제 정보 문제 위 그림은 여러 개의 컴퓨터들과 각 컴퓨터들을 잇는 회선을 나타냅니다. 각 회선들은 각각 품질이 다르며, 각 회선을 지날 때마다 신호에 있던 노이즈가 증폭될 수
algospot.com
정점에서 다른정점으로 가기 위한 회선을 지날 때 노이즈가 회선에 부여된 수 만큼 곱으로 증폭 된다.
0번째 정점에서 n-1번째 정점으로 가는 최소 증폭량을 구하는 문제이다.
다익스트라 알고리즘을 이용하면 쉽게 문제를 해결할 수 있다.
주의할 점은 곱연산으로 dist를 계산하기 때문에 초기 증폭값을 0이 아닌 1.0으로 두어야 한다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<iostream> | |
#include<vector> | |
#include<queue> | |
#include<limits> | |
using namespace std; | |
// 정점의 갯수 | |
int V; | |
// 인접리스트 | |
vector<pair<int, double>> adj[10000]; | |
// 각 정점까지의 최소 증폭량 구하는 다익스트라 알고리즘 | |
vector<double> dijkstra(int src) { | |
vector<double> dist(V, numeric_limits<double>::max()); | |
// 간선을 지날때마다 곱 연산을 해야하므로 초기 값 1.0 | |
dist[src] = 1.0; | |
// priority_queue<해당 정점까지의 증폭량, 정점번호> | |
priority_queue<pair<double, int>> pq; | |
// 우선순위 큐는 디폴트가 내림차순이므로 -1 곱해서 넣어준다 | |
pq.push(make_pair(-1.0, src)); | |
while (!pq.empty()) { | |
double cost = -pq.top().first; | |
int here = pq.top().second; | |
pq.pop(); | |
if (dist[here] < cost)continue; | |
for (int i = 0; i < adj[here].size(); i++) { | |
int there = adj[here][i].first; | |
// here에서 there로 갔을때 증폭량 | |
double nextDist = cost * adj[here][i].second; | |
// 이제까지 구한것 중에서 가장 작으면 우선순위큐에 넣는다. | |
if (dist[there] > nextDist) { | |
dist[there] = nextDist; | |
pq.push(make_pair(-nextDist, there)); | |
} | |
} | |
} | |
return dist; | |
} | |
int main() { | |
cout << fixed; | |
cout.precision(10); | |
int testcase; | |
cin >> testcase; | |
while (testcase--) { | |
int edges; | |
cin >> V >> edges; | |
for (int i = 0; i < V; i++) | |
adj[i].clear(); | |
int a, b; | |
double c; | |
for (int i = 0; i < edges; i++) { | |
cin >> a >> b >> c; | |
adj[a].push_back(make_pair(b, c)); | |
adj[b].push_back(make_pair(a, c)); | |
} | |
vector<double> output = dijkstra(0); | |
cout << output[V - 1] << endl; | |
} | |
} |
코드 원본: https://github.com/sbl133/JongmanBook/blob/main/30.%20ShortestPath/ROUTING.cpp
GitHub - sbl133/JongmanBook
Contribute to sbl133/JongmanBook development by creating an account on GitHub.
github.com

댓글을 통한 코드리뷰, 질문, 지적 언제든 환영입니다!
reference: 프로그래밍 대회에서 배우는 알고리즘 문제해결전략2
'Algorithm > algospot' 카테고리의 다른 글
algospot 보안종결자(문제 ID: NH) c++ (0) | 2022.03.01 |
---|---|
algospot 안녕히, 그리고 물고기는 고마웠어요!(문제 ID: SOLONG) c++ (0) | 2021.12.22 |
algospot 하노이의 탑 (문제 ID: HANOI4B) c++ (0) | 2021.10.29 |
algospot 어린이날 (문제 ID: CHILDRENDAY) c++ (0) | 2021.10.28 |
algospot Sorting Game(문제 ID: SORTGAME) c++ (0) | 2021.10.27 |