Under construction

Still being built. Things may change

The Cow Prom

Interview

Time limit1sMemory limit1024 MB

Summary
Given N cows and M directed ropes, count the groups of two or more cows where every cow can reach every other cow along the ropes.
Level

Medium4 of 10

Topics
Graph, DFS
Solved
No attempts yet

Problem

The NN (2≤N≤10,0002 \le N \le 10{,}000) cows are excited: it is prom night! They wear their finest gowns, with corsages and new shoes. Tonight each cow will try to perform the Round Dance.

Only cows can perform the Round Dance, which needs a set of ropes and a circular stock tank. The cows line up around the tank and number themselves consecutively from 1 to NN in clockwise order. Each cow faces the tank so she can see the other dancers.

The cows receive a total of MM (2≤M≤50,0002 \le M \le 50{,}000) ropes. Each rope is given to the cow who holds it in her hooves. Each cow hopes to hold one or more ropes in both her left and right hooves. Some cows may be disappointed.

For the dance to succeed for a cow (say, Bessie), the ropes she holds must be configured correctly. Check the cows at the other ends of her ropes, then the cows at the other ends of their ropes, and so on. When Bessie dances clockwise, she must instantly pull every other cow in her group clockwise too. If she dances counterclockwise, the entire group must be pulled counterclockwise.

A group can fail to form a proper dance. One case is when only one rope connects two cows. One cow can pull the other in one direction but cannot pull back, since pushing a rope does nothing. The cows must dance in lock-step. A dangling cow who is eventually pulled along, perhaps holding only one rope, disqualifies the group because she is not moving in step with the rest.

Given the ropes and who holds them, how many groups of cows can perform the Round Dance correctly? A set of ropes and cows may wrap around the tank many times.

Input

Line 1: two space-separated integers NN and MM.

Lines 2 to M+1M+1: each line has two space-separated integers AA and BB, describing a rope from cow AA to cow BB in the clockwise direction.

Output

A single line with one integer: the number of groups of cows that can successfully perform the Round Dance.

Examples1

  1. Example 1

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