Explanation
A simple brute-force approach would be to find the shortest path for all of the nodes, and then try to add a shortcut from to and find the shortest path again for all .
Using this approach, the answer is for all , where is the travel time that all cows take without a shortcut and represents the travel time that all cows take when there is a shortcut from to . Although this will certainly TLE, it hints at a faster way to compute the time saved.
Let's call the number of cows that pass through field and the cost for one cow to get from field to . Then the answer would be for all . This works because calculates the decrease in travel time for one cow to reach field . By multiplying this value by , we calculate the time decrease for all the cows that pass through that field.
We can find the values for quickly with Dijkstra's Algorithm. To determine , we'll store the parents of nodes while running Dijkstra's so we can backtrack to determine the counts of cows that pass through. We can compute in within the time limits because .
Implementation
Time Complexity:
C++
#include <bits/stdc++.h>using namespace std;int main() {freopen("shortcut.in", "r", stdin);freopen("shortcut.out", "w", stdout);int n, m, t;cin >> n >> m >> t;
Java
import java.io.*;import java.util.*;public class Shortcut {static long[] farms;static List<Edge>[] adj;public static void main(String[] args) throws IOException {Kattio io = new Kattio("shortcut");int N = 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!