문제: BOJ 15292 - Journey from Petersburg to Moscow
아이디어 요약
- 핵심 변환(α 트릭): 임계값
α를 두고 간선w를 비용max(0, w−α)로 바꾸면, 임의의 경로P에 대해 \(k·α + \sum_{e\in P} \max(0, w_e - α)\) 의 최소값을 구하는 문제가 된다. 이 표현을α에 대해 최소화하면P에서 가장 비싼 간선k개의 합과 같아진다. - 전역 최적화 교환: \(\min_P \min_α Φ_α(P) = \min_α \min_P Φ_α(P)\). 따라서 각
α마다 변환된 가중치로 최단경로를 구한 뒤k·α를 더하고, 모든 후보α에 대해 최소를 취하면 전역 최적해가 된다. - 후보
α집합:Φ_α는 간선 가중치에서만 기울기가 바뀌므로α ∈ {0} ∪ {모든 w}만 확인해도 충분하다. - 알고리즘: 각
α에 대해 가중치max(0, w−α)로 다익스트라를 수행해dist[n]을 구하고,ans = min(ans, dist[n] + k·α)를 갱신한다.
C++ 풀이
| |
복잡도
α후보 수 ≤m + 1 (가중치 종류 + 0)- 각 다익스트라
O((n + m) log n)→ 전체O((m + 1) · (n + m) log n) - 제약
n, m ≤ 3000에서 충분히 빠르게 동작
빌드/실행
- 빌드:
g++ -O2 -pipe -static -s -std=gnu++17 main.cpp -o main - 실행:
./main < input.txt > output.txt
![Featured image of post [Algorithm] C++ 백준 15292번 : Journey from Petersburg to Moscow](/post/algorithm/2025-08-12-boj-15292-journey-from-petersburg-to-moscow-cpp-solution/wordcloud_hu_905ebcea368a02b2.png)
![[Algorithm] C++ 백준 14737번 Dev, Please Add This!](/post/algorithm/2025-08-12-boj-14737-dev-please-add-this-cpp-solution/wordcloud_hu_ba04f1851bf25036.png)
![[Algorithm] C++ 백준 14960번 - Strongly Matchable](/post/algorithm/2025-08-12-boj-14960-strongly-matchable-cpp-solution/wordcloud_hu_ac286532be0bb43d.png)
![[Algorithm] C++ 백준 15292번 : Journey from Petersburg to Moscow](/post/algorithm/2025-08-12-boj-15292-journey-from-petersburg-to-moscow-cpp-solution/wordcloud_hu_4347fd439205a4e9.png)
![[Algorithm] C++ 백준 15521번 : Revenge of the Broken Door](/post/algorithm/2025-08-12-boj-15521-revenge-of-the-broken-door-cpp-solution/wordcloud_hu_faa1bd80d20ea1e1.png)
![[Algorithm] C++ 백준 15737번 : 일반 그래프 매칭](/post/algorithm/2025-08-12-boj-15737-general-graph-matching-cpp-solution/wordcloud_hu_547506eb22f83b30.png)
![[Algorithm] C++ 백준 12670번 : The Year of Code Jam (Large)](/post/algorithm/2025-08-12-boj-12670-the-year-of-code-jam-large-cpp-solution/wordcloud_hu_b283724f94c025d6.png)
![[Algorithm] C++ 백준 14510번 : Blazing New Trails](/post/algorithm/2025-08-12-boj-14510-blazing-new-trails-cpp-solution/wordcloud_hu_b53a0a28b4b300e.png)
![[Algorithm] C++ 백준 16041번 : Double Clique](/post/algorithm/2025-08-12-boj-16041-double-clique-cpp-solution/wordcloud_hu_4d21b4066145dfb5.png)
![[Algorithm] C++ 백준 17642번 : Dynamic Diameter](/post/algorithm/2025-08-12-boj-17642-dynamic-diameter-cpp-solution/wordcloud_hu_aed53ad73c5517bf.png)