Under construction

Still being built. Things may change

Treetop Walkway

Time limit5sMemory limit512 MB

Summary
Given a weakly connected directed graph, find the minimum number of edges to add so every vertex reaches every other.
Level

Medium7 of 10

Topics
Graph, Greedy, DFS
Solved
No attempts yet

Problem

The amusement park keeps wide patches of forest between its attractions. A treetop walkway lets visitors move through the canopies and look out over the hills and lakes around the park.

The walkway is built from wooden platforms fixed near the treetops at different heights above the ground, joined by narrow wooden paths. Each path joins exactly two platforms, and the number of paths meeting at a platform differs from platform to platform. Ignoring the direction of travel, every platform can be reached from every other platform along the paths.

To raise the safety standard and to relieve crowding at a few spots, the management made every path strictly one way. Once the directions were fixed, a problem showed up. Walking only in the prescribed directions, some platforms can no longer be reached from some other platforms. The management chose the directions on aesthetic and operational grounds, so the directions stay as they are.

The repair is to build extra one way paths between platforms that already exist. No platform is added and no old path changes direction. After the new paths are built, every platform must be reachable from every other platform along the paths. The management wants to build as few new paths as possible.

Find that smallest number of new paths.

Input

The input holds several test cases and ends at the end of the file.

Each test case starts with a line holding two integers NN and MM (1≤N≤1051 \le N \le 10^5, 0≤M≤2⋅1050 \le M \le 2 \cdot 10^5), the number of platforms and the number of existing paths. The platforms are labeled 11 through NN.

Each of the next MM lines holds two different platform labels AA and BB, which means there is a one way path leading from AA to BB. Inside one test case the ordered pair (A,B)(A, B) never appears twice, but A→BA \to B and B→AB \to A may both appear. Ignoring the directions, the paths of a test case connect all NN platforms.

Output

For each test case, print one line holding a single integer RR, the smallest number of new one way paths that makes every platform reachable from every other platform. Print only this number. You do not have to print the new paths themselves.

Examples3

  1. Example 1

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

    Input
    1 0
    
    Expected output
    0
  3. Example 3

    Input
    3 3
    1 2
    2 3
    3 1
    
    Expected output
    0