Explanation
- Use Dijkstra's to calculate distances from , , and .
- Consider a subset of directed edges where each directed edge is part of a shortest path from to . Note that this subset is a DAG, and can be found by keeping track of the parents of every node when running Dijkstra's with as the starting node.
- An optimal path will either be in the form or , where is a path on the DAG. Note that any path on the DAG is a valid commuter pass option.
- Without loss of generality, assume that our path has the form .
- Define as the minimum distance from to any node such that is on a path from to in the DAG.
- Define as the minimum distance from to if the commuter pass edges used are on a path from to in the DAG.
- For each parent of a node , our transitions are:
- If the source node is , then the answer is . To handle the case where the optimal path has the form , we repeat the algorithm for the source node .
- Alternatively, the answer could be the distance from to without using the commuter pass.
Implementation
Time Complexity:
C++
#include <bits/stdc++.h>typedef long long ll;using namespace std;vector<pair<ll, ll>> graph[100001];ll du[100001], dv[100001], ds[100001], dp[2][100001], ans;bool visited[100001];void dijkstra1(ll start, ll arr[]) {fill(visited, visited + 100001, false);
Alternatively, Nathan's implementation. Note that the DP definitions in Nathan's implementation are slightly different than above.
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!