Solution 1 - Kruskal's
Explanation
We first notice that movement is defined in terms of portals, so we mainly care about how the portals are connected.
Let's consider the undirected multigraph with nodes such that:
- Every portal in the original graph corresponds to a node in
- Every node in the original graph corresponds to edges and in
We observe that each node in has degree exactly two, so is a union of disjoint cycles. Thus, our goal is to join all nodes in into a single cycle.
Let's suppose that portals and are not contained within the same cycle as and in .
Then, by permuting the portals adjacent to node such that the adjacency list becomes , we can combine all of into a single cycle. Essentially, each node can unite two cycles.
Notice that by replacing "cycles" with "connected components" above, we are encouraged to find a Minimum Spanning Tree (MST). In other words, we wish to unite all disjoint connected components such that becomes connected.
Now, let's consider the graph with the same nodes as and the following costs:
- For each node , edges and have cost
- For each node , edge has cost moonies
Specifically, the answer is the cost of the MST of , which can be found using Kruskal's algorithm or Prim's algorithm.
Implementation
Time Complexity:
C++
#include <algorithm>#include <iostream>#include <vector>using namespace std;struct Edge {int from, to, cost;};const int MAX_N = 100000;int parent[MAX_N * 2];
Solution 2 - Prim's
Time Complexity:
C++
#include <iostream>#include <queue>#include <vector>using namespace std;const int MAX_N = 100000;struct Node {int vertex, cost;bool operator>(Node other) const { return cost > other.cost; }};
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!