Table of Contents

ExplanationImplementation

Official Analysis (C++)

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 11 to ii and find the shortest path again for all ii.

Using this approach, the answer is min(distshorti)\min(\texttt{dist}-\texttt{short}_i) for all ii, where dist\texttt{dist} is the travel time that all cows take without a shortcut and shorti\texttt{short}_i represents the travel time that all cows take when there is a shortcut from 11 to ii. Although this will certainly TLE, it hints at a faster way to compute the time saved.

Let's call occi\texttt{occ}_i the number of cows that pass through field ii and travi\texttt{trav}_i the cost for one cow to get from field ii to 11. Then the answer would be max(occi(traviT))\max(\texttt{occ}_i \cdot (\texttt{trav}_i - T)) for all ii. This works because traviT\texttt{trav}_i - T calculates the decrease in travel time for one cow to reach field 11. By multiplying this value by occi\texttt{occ}_i, we calculate the time decrease for all the cows that pass through that field.

We can find the values for travi\texttt{trav}_i quickly with Dijkstra's Algorithm. To determine occi\texttt{occ}_i, 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 occ\texttt{occ} in O(N2)\mathcal{O}(N^2) within the time limits because N104N \leq 10^4.

Implementation

Time Complexity: O(MlogN+N2)\mathcal{O}(M\log N + N^2)

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!