USACO Silver 2020 January - Wormhole Sort
Authors: Óscar Garries, Neo Wang, Kevin Sheng
Appears In
Solution 1 - Binary Search and Floodfill
Time Complexity:
Implementation
C++
#include <fstream>#include <iostream>#include <vector>using std::cout;using std::endl;using std::vector;int main() {std::ifstream read("wormsort.in");
Java
Warning!
Due to Java's relatively slow speed, the below solution will often TLE on some test cases.
import java.io.*;import java.util.*;public class WormSort {public static void main(String[] args) throws IOException {Kattio io = new Kattio("wormsort");int cowNum = io.nextInt();int wormholeNum = io.nextInt();
Solution 2 - Binary Search and DSU
Like the floodfill solution, we binary search on the answer , which is valid if all are in the same component as , which we can query in using a Disjoint Set Union.
Implementation
Time Complexity:
C++
#include <fstream>#include <iostream>#include <vector>using std::cout;using std::endl;using std::vector;Code Snippet: DSU (Click to expand)
Java
import java.io.*;import java.util.*;public class WormSort {public static void main(String[] args) throws IOException {Kattio io = new Kattio("wormsort");int cowNum = io.nextInt();int wormholeNum = io.nextInt();
Solution 3 - DSU
Due to the DSU's fast query and linking complexity, we can drop the binary search and instead add wormholes from greatest width to least width until all are in the same component as .
Implementation
Time Complexity:
C++
#include <algorithm>#include <fstream>#include <iostream>#include <vector>using std::cout;using std::endl;using std::vector;Code Snippet: DSU (Click to expand)
Java
import java.io.*;import java.util.*;public class WormSort {public static void main(String[] args) throws IOException {Kattio io = new Kattio("wormsort");int cowNum = io.nextInt();int wormholeNum = io.nextInt();
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!