Skip to content

Commit 21b5467

Browse files
Merge pull request #256 from cpinitiative/content/commuter-pass-sol
content: add commuter pass solution notes
2 parents 5d10445 + b1766f2 commit 21b5467

File tree

1 file changed

+14
-3
lines changed

1 file changed

+14
-3
lines changed

solutions/JOI 18-commuter-pass.mdx

+14-3
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,22 @@
11
---
22
id: joi-18-commuter-pass
33
title: JOI 2018 Commuter Pass
4-
author: Andi Qu
4+
author: Andi Qu, Nathan Wang
55
---
66

7-
<IncompleteSection />
7+
1. Use Dijkstra's to calculate distances from $s$, $u$, and $v$.
8+
2. Consider a subset of directed edges where each directed edge is part of a shortest path from $s$ to $t$. Note that this subset is a DAG, and can be found by keeping track of the parents of every node when running Dijkstra's.
9+
3. Note that an optimal path will be $u \rightarrow x \rightarrow y \rightarrow v$, where $x \rightarrow y$ is a path on the DAG. Note that any path on the DAG is a valid commuter pass option, and the only node with in-degree 0 is $u$, and the only node with out-degree 0 is $t$ in the DAG.
10+
4. Define `dpU(i)` = minimum distance from $u$ to any node $x$ such that $x$ is in a path from $s$ to $i$ in the DAG.
11+
5. Define `dpV(i)` = minimum distance from $v$ to any node $x$ such that $x$ is in a path from $s$ to $i$ in the DAG.
12+
6. The DP transition for `dpU(i)` is `dpU(i) = min(distU[i], dpU(parent_i))` for each parent of `i` (see `dijkstra2` function implementation for more details). `dpV`'s transition is defined similarly.
13+
7. Our answer is `dpU(v) + dpV(v)`. Since edges are bidirectional, an optimal path can also be $v \rightarrow x \rightarrow y \rightarrow u$ where $x \rightarrow y$ is a path on the DAG. We can solve this by rerunning steps 2-7 while switching $u$ and $v$. In Andi's code, steps 2-7 are implemented in the `dijkstra2` function.
14+
8. Alternatively, the answer could just be from $u$ directly to $v$ without using the commuter pass.
815

916
## Code
1017

18+
Andi's implementation:
19+
1120
```cpp
1221
#include <bits/stdc++.h>
1322
typedef long long ll;
@@ -90,4 +99,6 @@ int main() {
9099
cout << ans << '\n';
91100
return 0;
92101
}
93-
```
102+
```
103+
104+
Alternatively, [Nathan's implementation](https://github.com/thecodingwizard/competitive-programming/blob/master/JOI/JOI%2018-commuterpass.cpp). Note that the DP definitions in Nathan's implementation are slightly different than above.

0 commit comments

Comments
 (0)