Islands Tour
InterviewTime limit1sMemory limit1024 MB
In a directed graph where each island has at most one outgoing zip-line, find the most distinct islands a tour starting anywhere can visit.
- Level
Medium5 of 10
- Topics
- Graph, DFS, Implementation
- Solved
- No attempts yet
Problem
There are beautiful islands connected with zip-lines. A tourist can go from one island to another island sliding through a zip-line that connects the islands. Sliding through a zip-line above sunset sea, a tourist can see breathtaking sceneries of nature with twinkling lights over the sunlit sea waters. These islands are fantastic attractions among tourists. Each island is full of flowers of numerous colors. Travelling from an arbitrary island, a tourist called Optimizer wants to visit as many distinct islands as possible.
The islands are represented as a directed graph . A zip-line from an island to another island is represented as a directed edge . We assume that each island has at most one outgoing zip-line, that is, for each vertex , we have at most one outgoing edge.
For example, the figure below shows an example of the islands represented as a directed graph.

The dotted path in the following graph denotes a longest tour that visits as many distinct islands as possible.

Given a directed graph that represents the islands and their connections using zip-lines, write a program to output the maximum number of islands that can be visited by Optimizer. Note that Optimizer can start from an arbitrary island and cannot visit the same island twice or more.
Input
Your program reads from standard input. The input starts with a line containing two integers, and (), where is the number of zip-line connections (edges) and is the number of islands (vertices). The islands are numbered from to . In the following lines, the -th line contains two integers and that represent a directed edge from to . Each vertex has at most one outgoing edge.
Output
Your program writes to standard output. Print exactly one line. The line contains the maximum number of distinct islands that can be visited by riding zip-lines starting from an arbitrary island.