#K94167. Max Rooms Unlocked
Max Rooms Unlocked
Max Rooms Unlocked
You are given a building with N rooms and N keys. Each key i (1-indexed) can unlock a room numbered Ki. Initially, key i is placed in room Ui. When you are in a room, you can pick up all keys located there and use them to unlock their associated rooms. Starting from room 1, you want to maximize the number of rooms you can access.
You are allowed to reassign exactly M keys to different rooms. In other words, you must choose exactly M keys and change the room in which each is placed (the new room number must be different from its original one). After making these modifications, a key placed in room r will unlock room Ki (for key i), creating a directed edge from r to Ki. Your task is to determine the maximum number of rooms that can be unlocked (i.e. reached) starting from room 1.
Note: All formulas are presented in LaTeX format. For example, the unlocking relation for a key is given by: \( r \rightarrow K_i \), where \( r \) is the room the key is placed in.
inputFormat
The input is given via stdin in the following format:
- The first line contains two integers \(N\) and \(M\), where \(N\) is the number of rooms (and keys) and \(M\) is the exact number of keys you must modify.
- The second line contains \(N\) integers, representing the array \(K\), where the \(i\)th integer is the room that key \(i\) can unlock.
- The third line contains \(N\) integers, representing the array \(U\), where the \(i\)th integer denotes the initial room in which key \(i\) is placed.
outputFormat
Output a single integer to stdout: the maximum number of rooms that can be unlocked (i.e., reached) starting from room 1 after exactly \(M\) key modifications.
## sample5 1
2 3 4 5 1
1 2 3 4 5
5