This page is still under construction.

Parts of this page are still being built. What you see may change.

Ranking the Cows

Time limit1sMemory limit128 MB

Summary
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 NN cows (1≤N≤10001 \le N \le 1000), 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 MM pairs of cows (1≤M≤100001 \le M \le 10000). He now wants to prepare a list of CC additional pairs of cows such that, once he also compares those CC pairs, he will definitely be able to deduce the complete ordering of all NN cows. Determine the minimum value of CC for which such a list is possible.

Input

  • Line 1: Two space-separated integers NN and MM.
  • Lines 2..M+1: Two space-separated integers XX and YY (1≤X,Y≤N1 \le X, Y \le N), describing a known comparison in which cow XX was ranked higher (produces milk more quickly) than cow YY.

Output

  • Line 1: A single integer, the minimum value of CC.

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?"

Examples2

  1. Example 1

    Input
    5 5
    2 1
    1 5
    2 3
    1 4
    3 4
    
    Expected output
    3
    
  2. Example 2

    Input
    2 1
    1 2
    
    Expected output
    0