#P2607. Knight Team Selection
Knight Team Selection
Knight Team Selection
Z nation's knights are a force to be reckoned with. They come from all corners of the land, and each knight detests exactly one other knight – his most hated comrade – and will never join a battle alongside that individual. Now, with the evil Y nation invading and conflict raging across the land, the king has charged you with the task of assembling a conflict‐free battalion of knights that possesses the highest possible combat power.
Each knight is numbered from 1 to n and has an estimated combat power. The overall strength of a knight team is the sum of the combat powers of all selected knights. However, for every knight i you select, you must ensure that his most hated knight f(i) is not selected.
Input begins with a single integer n. The next line contains n space-separated integers representing the combat power of each knight. The third line contains n space-separated integers, where the i-th integer (1-indexed and not equal to i) indicates the knight that knight i despises.
Your task is to select a subset of knights (i.e. a knight team) that complies with the no-conflict condition and that maximizes the total combat power.
Note: Due to the structure of the hatred relation – where every knight hates exactly one other – the knights form a functional graph that is a union of cycles with trees attached. You may need to use a combination of tree dynamic programming and cycle DP (with a "house robber" style recurrence) to solve the problem.
inputFormat
The first line contains a single integer n. The second line contains n space-separated integers representing the combat power of each knight. The third line contains n space-separated integers, where the i-th integer is the knight that knight i despises (1-indexed, and f(i) ≠ i).
outputFormat
Output a single integer representing the maximum total combat power achievable by selecting a conflict-free team of knights.
sample
3
1 2 3
2 3 1
3