#DSU0000029. Bài toán quỷ nhện – phiên bản khó (Medium Demon Problem (hard version))
Bài tập thuộc lộ trình
Mục lục đề ⌄
Bài toán quỷ nhện – phiên bản khó (Medium Demon Problem (hard version))
Medium Demon Problem (hard version)
Source: Codeforces
Version: Phuoc Hung OJ Extended
Problem Statement
There are spiders numbered from to . Initially, each spider owns exactly one toy. Spider has a fixed recipient , which is different from .
Each year, every spider possessing at least one toy simultaneously sends exactly one toy to spider . A spider with no toys sends nothing. All incoming toys arrive only after every spider has finished sending for that year. A spider may hold multiple toys. The state of the system is the number of toys held by each spider.
Year is called stable if the state immediately before the transfers of year is identical to the state immediately before year . Year is not stable by definition. Find the first stable year.
Input
The first line contains , the second with and .
Output
Print the index of the first stable year.
Subtasks
- Subtask 1 (20 points): ; and .
- Subtask 2 (30 points): ; and .
- Subtask 3 (50 points): ; and .
Examples
Input
5
2 1 4 2 3
Output
5
Explanation
The toy counts just before years are , , , , and , respectively. Year is the first year whose starting state is identical to that of the preceding year, so the answer is 5.