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, x 1 ;x 2 ;:::;x n (1 x i s ): the
recorded playlist history. Output Per testcase: 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 .
排除掉所有不可能的答案,剩下的便是解。
如果一个答案不可能,那么一定是把两个相同的数放在了同一个区间里。考虑每一对相邻的相同的且间距小于s的数,则他们之间一定被划开。那么除了他们之间的界线,其他界线一定是非法的【因为会把他们两个划在一起】。
注意排除掉连续区间时的循环问题。
方法一见这里
#include<cstdio>
#include<cstring>
#define M(a) memset(a,0,sizeof(a))
int fir[100010],ne[100010],a[100010];
bool b[100010];
int main()
{
int i,j,k,m,n,p,q,x,y,z,T,tot,ans,s,l,r;
scanf("%d",&T);
while (T--)
{
M(fir);
M(ne);
M(a);
memset(b,1,sizeof(b));
scanf("%d%d",&s,&n);
for (i=1;i<=n;i++)
scanf("%d",&a[i]);
for (i=n;i>=1;i--)
{
ne[i]=fir[a[i]];
fir[a[i]]=i;
}
for (k=1;k<=s;k++)
{
for (i=fir[k];ne[i];i=ne[i])
{
if (ne[i]-i>=s) continue;
l=i%s;
r=(ne[i]%s-1+s)%s;
if (l<=r)
{
for (j=0;j<l;j++) b[j]=0;
for (j=r+1;j<s;j++) b[j]=0;
}
else
for (j=r+1;j<l;j++) b[j]=0;
}
}
ans=0;
for (i=0;i<s;i++)
if (b[i]) ans++;
printf("%d\n",ans);
}
}