Intact Intervals
Time limit6sMemory limit1024 MB
Count the ways to cut a circular array into at least two contiguous arcs so that each arc's multiset equals the corresponding multiset of the target array b.
- Level
Hard8 of 10
- Topics
- Array, Hash map, Prefix sum, Combinatorics
- Solved
- No attempts yet
Problem
Gustav is an astronaut on the Nordic Celestial Planetary Craft (NCPC), a large space station in orbit around Mars. Today, one of Gustav's tasks is to look over the safety routines on board.
The space station consists of modules arranged in a circle, so that module is connected to module for , and module is connected to module . Each module has a non-negative integer type , representing the kind of equipment that can be found there. Different modules can have the same type. In case of emergency, the equipment must be rearranged so that each module instead gets type , for some list . Here, the list is a rearrangement of the list .
Gustav has noticed that if some module connections are severed, causing the space station to split into separate parts, it may become impossible to perform this rearrangement of the equipment. He decides to estimate how likely it is that the safety routines can be followed, by calculating in how many ways the space station can be separated into two or more parts such that it is still possible to rearrange the equipment according to the emergency procedures.
In other words, your task is to count in how many ways the circular list can be partitioned into at least two non-empty contiguous intervals, in such a way that the circular list can be obtained by rearranging elements within each interval. Since this number can be quite big, you should find its remainder modulo .
For example, consider Sample Input 1 below. Here the list could be split into , indicating that the connection between modules and , and the connection between modules and , are severed. Note that the connection between module and remains in this split. The second possible way in which could be split is .
In Sample Input 2 below, the only possible way to split the list into at least two non-empty parts is to separate the two modules. But then it is impossible to rearrange the parts to create the list . Hence, the answer is .
Input
The first line of input contains a single integer (), the number of modules. The second line contains the integers (). The third and final line contains the integers ().
The list is guaranteed to be a rearrangement of the list .
Output
Print one integer, the number of safe separations modulo .