problems / 261

One-Way Streets of the New District

medium graphs scc dfs 1000 ms · 256 MB

One-Way Streets of the New District

A new district has n intersections, numbered from 1 to n, and m one-way streets. Street i leads from intersection u_i to intersection v_i and can only be driven in that direction.

The planners want every intersection to be reachable from every other intersection by driving along streets in their allowed directions. To get there they can build new one-way streets, each between any two intersections of their choice, in either direction.

What is the fewest new streets they have to build?

Input

The first line contains two integers n and m (1 ≤ n ≤ 2·10^5, 0 ≤ m ≤ 2·10^5).

Each of the next m lines contains two integers u_i and v_i (1 ≤ u_i, v_i ≤ n): a one-way street from u_i to v_i. A street may start and end at the same intersection, and several streets may connect the same pair of intersections.

Output

Print a single integer: the minimum number of one-way streets to add so that every intersection can reach every other one.

Notes

In the first example, intersections 1, 2 and 3 form a loop, and intersections 4 and 5 hang off it: 4 can be reached from the loop but cannot get back, and 5 can reach the loop but cannot be reached from it. One new street from 4 to 5 fixes both problems.

In the second example, every intersection can already reach every other one, so nothing has to be built.

The district can be a single long chain of streets, so a recursive search may run out of stack space.

Example 1

Input

5 5
1 2
2 3
3 1
3 4
5 1

Output

1

Example 2

Input

4 6
1 2
2 3
3 4
4 1
2 2
2 3

Output

0

Hints · reveal one at a time if you're stuck

Hint 1

Intersections that can already reach each other behave like one big intersection. What does the street map look like after you merge each such group into a single node?

Hint 2

After merging, the map has no cycles. A group that no street enters must receive a new street, and a group that no street leaves must get a new street out of it. Is that lower bound always achievable? Don't forget the case where there is only one group.

Hint 3

The groups are the strongly connected components, found in linear time with Tarjan's algorithm. Write the DFS iteratively, since the map can be one long chain.

report an issue Prefer your own editor? sooks prep 261 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.