Piggy Banks
InterviewTime limit3sMemory limit128 MB
Each key i sits in some bank; opening a bank frees its keys. Find the minimum number of banks to smash to reach all N banks.
- Level
Medium5 of 10
- Topics
- Graph, DFS, Union-find, Implementation
- Solved
- No attempts yet
Problem
Byteazar the Dragon has piggy banks. Each piggy bank can either be opened with its corresponding key or smashed. Byteazar has placed the keys inside some of the piggy banks, and he remembers exactly which key is in which piggy bank. He intends to buy a car and needs to gain access to all of the piggy banks, but he wants to destroy as few of them as possible.
Once a piggy bank is open (whether unlocked with its key or smashed), the keys inside it can be taken out and used to open the corresponding piggy banks without smashing them, and this repeats in a chain. Determine the minimum number of piggy banks that must be smashed to gain access to all of them.
Write a program which:
- reads from standard input the number of piggy banks and, for each key, the piggy bank that holds it,
- finds the minimal number of piggy banks that must be smashed in order to gain access to all of them,
- writes the outcome to standard output.
Input
The first line contains a single integer () - the number of piggy banks. The piggy banks (and their corresponding keys) are numbered from to . Each of the next lines contains one integer: the -th of these lines gives the number of the piggy bank in which key has been placed.
Output
Output a single integer - the minimal number of piggy banks that must be smashed in order to gain access to all of them.
Hint
For the sample input, piggy banks and must be smashed. Smashing bank yields key , which opens bank ; bank contains keys and , which open banks and . Bank holds only its own key, so it must be smashed separately.