UVa OJ 12174 - Shuffle
Problem
You are listening to your music collection using the shuffle function to keep the music surprising. You assume that the shuffle algorithm of your music player makes a random permutation of the songs in the playlist and plays the songs in that order until all songs have been played. Then it reshuffles and starts playing the list again.
You have a history of the songs that have been played. However, your record of the history of played songs is not complete, as you started recording songs at a certain point in time and a number of songs might already have been played. From this history, you want to know at how many different points in the future the next reshuffle might occur.
A potential future reshuffle position is valid if it divides the recorded history into intervals of length s (the number of songs in the playlist) with the rst and last interval possibly containing less than s songs and no interval contains a specic song more than once.
Input
On the rst line one positive number: the number of testcases, at most 100. After that per testcase:
• One line with two integers s and n (1 ≤ s, n ≤ 100000): the number of different songs in the playlist and the number of songs in the recorded playlist history.
• One line with n space separated integers, x1, x2, . . . , xn (1 ≤ xi ≤ s): the recorded playlist history.
Output
One line with the number of future positions the next reshuffle can be at. If the history could not be generated by the above mentioned algorithm, output 0.
Sample Input
1 | 4 |
Sample Output
1 | 1 |
Solution
一开始没想太多,直接用枚举的方式,写了一下代码,提交之后虽然AC了,但是耗时2s多,内心还是不舒服的。于是尝试改了一下,也参考了别人的代码。
总体说来还是一道滑动窗口的题目,并不是十分复杂,但是处理得当的话,效率能提升很多。这里为了节省时间,通过一次扫描,将每一段可以构成音乐单的数字,用idx这个数组来保存,可以为1,不行则为0.最后再将第一个数字按顺序,先当成第一段的最后一个,再当成第一段的倒数第二个,以此类推,得到结果。
1 |
|