Ranking the Cows
Time limit1sMemory limit128 MB
Given partial comparison results between N cows with distinct milk rates, find the minimum number of additional pairwise comparisons needed to determine the full ranking.
- Level
Medium6 of 10
- Topics
- Graph, Topological sort, Sorting, Combinatorics
- Solved
- No attempts yet
Problem
Farmer John has cows (), each producing milk at a different positive rate. FJ would like to order his cows from the fastest milk producer to the slowest.
He has already compared the milk output rates of pairs of cows (). He now wants to prepare a list of additional pairs of cows such that, once he also compares those pairs, he will definitely be able to deduce the complete ordering of all cows. Determine the minimum value of for which such a list is possible.
Input
- Line 1: Two space-separated integers and .
- Lines 2..M+1: Two space-separated integers and (), describing a known comparison in which cow was ranked higher (produces milk more quickly) than cow .
Output
- Line 1: A single integer, the minimum value of .
Hint
Suppose FJ is comparing 5 cows and has already determined that cow 2 > cow 1, cow 1 > cow 5, cow 2 > cow 3, cow 1 > cow 4, and cow 3 > cow 4 (where '>' means "produces milk more quickly").
From these 5 results, FJ knows that cow 2 has the highest rank, since cow 2 > cow 1 > cow 5 and cow 2 > cow 3 > cow 4. However, he still needs to compare cow 1 with cow 3 to decide the second-highest cow, one more comparison to order cow 4 and cow 5, and (if cow 1 outranks cow 3) a comparison of cow 5 with cow 3. He therefore must ask three questions to be certain of the full ranking: "Is cow 1 > cow 3? Is cow 4 > cow 5? Is cow 5 > cow 3?"