Rank

Interview

Time limit2sMemory limit1024 MB

Summary
Count the players that lie on a directed win cycle built from the game results.
Level

Medium4 of 10

Topics
Graph, DFS
Solved
No attempts yet

Problem

A tournament has NN players and KK games. Each game is played by two different players. A player may play any number of games and does not have to meet every opponent. A player may play no game at all. There is no draw, so every game has one winner and one loser.

Once all the games are over, the players are ranked. Ranking can fail for several reasons, but this problem deals only with cycles of wins. For example, if A beats B, B beats C, and C in turn beats A, the relative ranking of these three players cannot be determined.

Stated precisely, suppose there are distinct players P1,P2,…,PmP_1, P_2, \dots, P_m (m≥2m \ge 2) such that P1P_1 beat P2P_2, P2P_2 beat P3P_3, and so on until PmP_m beat P1P_1. The ranking of those mm players cannot be determined because of the cycle. The case m=2m = 2 happens when two players met twice and each of them won once. One player may belong to several cycles at the same time, and such a player is counted once.

Only players caught in a cycle are counted. A player whose ranking is undetermined for a different reason, for example a player who played no game, is not counted.

Given the list of games and their results, write a program that finds how many players have an undetermined ranking because of a cycle.

Input

The first line contains the number of players NN and the number of games KK, separated by a space. (2≤N≤202 \le N \le 20, 1≤K≤301 \le K \le 30) The players are numbered 11 through NN.

Each of the next KK lines contains the result of one game as four integers aa, bb, sas_a, sbs_b. Here aa and bb are the numbers of the two players, and sas_a and sbs_b are the scores of player aa and player bb. Every score is a non-negative integer smaller than 1010, and the player with the larger score wins.

Output

Print the number of players whose ranking cannot be determined because of a cycle.

Examples4

  1. Example 1

    Input
    10 12
    1 8 2 1
    1 2 5 0
    10 7 1 2
    6 9 6 9
    3 4 3 1
    9 5 3 1
    8 2 6 8
    4 9 3 0
    4 1 5 2
    6 10 3 5
    3 5 1 9
    6 7 9 8
    
    Expected output
    7
    
  2. Example 2

    Input
    5 3
    1 3 9 7
    5 1 9 2
    3 5 2 0
    
    Expected output
    3
    
  3. Example 3

    Input
    5 6
    1 2 2 1
    1 5 2 1
    1 3 2 1
    5 2 0 5
    5 3 1 8
    2 4 4 2
    
    Expected output
    0
    
  4. Example 4

    Input
    10 5
    2 4 0 2
    2 6 5 3
    8 2 8 2
    6 4 6 2
    8 6 0 2
    
    Expected output
    4