Video Solution
Note: The video solution might not be the same as other solutions. Code in C++.
In the sample input, we have the following cows: , and there's two ways to pair these up.
The first case would take time units to finish milking all cows.
The second case would take time units to finish milking all cows.
This test case consists of 3 distinct values: , let's call them . These would follow the paradigm .
Therefore, .
We should always pair up the greatest value (), with the smallest value (), in order to achieve the most optimal milking time.
Implementation
Time Complexity:
(Because it requires sorting the input, which is ).
C++
#include <algorithm>#include <cmath>#include <fstream>#include <iostream>#include <vector>using namespace std;typedef pair<int, int> pii;int main() {
Python
import syssys.stdin = open("pairup.in", "r")sys.stdout = open("pairup.out", "w")n = int(input())all_cows = []for _ in range(n):num_cows, milk_time = map(int, input().split())all_cows.append([milk_time, num_cows])
Java
import java.io.*;import java.util.*;public class PairUp {public static void main(String[] args) throws IOException {BufferedReader io = new BufferedReader(new FileReader("pairup.in"));int N = Integer.parseInt(io.readLine().trim());List<Pair> events = new ArrayList<>();for (int i = 0; i < N; i++) {StringTokenizer tok = new StringTokenizer(io.readLine());
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!