Grass Cownoisseur
Time limit1sMemory limit256 MB
Starting from field 1 and returning to it, visit the most distinct fields while traveling at most one directed path backwards.
- Level
Medium7 of 10
- Topics
- Graph, Topological sort, Dynamic programming
- Solved
- No attempts yet
Problem
Farmer John installed one-way cow paths all over his farm to manage how his cows graze. The farm has fields numbered through , and each path connects a pair of fields. If a path runs from field to field , cows may travel from to but not from to .
Bessie the cow wants to eat grass in as many fields as possible. She starts her day in field , walks through a sequence of fields, and returns to field at the end of the day. She eats the grass of a field only the first time she is there, so she tries to maximize the number of distinct fields on her route.
The one-way rule cuts down how many fields Bessie reaches in one day. She wonders how much grass she gets if she breaks the rule and follows one path in the wrong direction. Compute the largest number of distinct fields on a route that starts and ends at field when she may follow at most one path in the wrong direction. She travels backwards at most once per day, so she cannot take the same path backwards twice either.
Input
The first line contains the number of fields and the number of one-way paths . ()
Each of the next lines describes one path with two distinct field numbers and , meaning there is a path from to . The same path never appears more than once.
Output
Print one line with the maximum number of distinct fields Bessie visits on a route that starts and ends at field and follows at most one path in the wrong direction.
Hint
Here is a drawing of the farm in the first example.
v---3-->6
7 |\ |
^\ v \ |
| \ 1 \|
| \| v
| v 5
4<--2---^
Bessie can walk by traveling backwards on the path between and . Once she reaches field she cannot get to field without following another path backwards.