Treetop Walkway
Time limit5sMemory limit512 MB
Given a weakly connected directed graph, find the minimum number of edges to add so every vertex reaches every other.
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 and (, ), the number of platforms and the number of existing paths. The platforms are labeled through .
Each of the next lines holds two different platform labels and , which means there is a one way path leading from to . Inside one test case the ordered pair never appears twice, but and may both appear. Ignoring the directions, the paths of a test case connect all platforms.
Output
For each test case, print one line holding a single integer , 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.