我有话说:
这道题运用了滑动窗口这一技巧。转载了刘汝佳大神的代码。做了一下翻译。
#include<iostream>
#include<vector>
using namespace std;
const int maxn = 100000 + 5;
int s, n, x[maxn*3], cnt[maxn], ok[maxn*2];
int main() {
int T;
cin >> T;
while(T--) {
cin >> s >> n;
//可能上一段还有歌,但是没记录,我们初始为-1
// so we don't have to worry about negative subscript or wrapping round
//并且从s开始储存,我们就不用担心负数的下标或者还没有结束的一段
fill(x, x+n+2*s, -1);
for(int i = 0; i < n; i++) cin >> x[i+s];
int tot = 0; // 统计在滑动窗口中的不一样的数字的个数
fill(cnt+1, cnt+s+1, 0); // cnt[i]保存数字i在窗口中出现的次数
fill(ok, ok+n+s+1, 0); // ok[i] = 1 当如果窗口中没有相同的数,那么一定是一个排列
//更新ok数组
for(int i = 0; i < n+s+1; i++) {
if (tot == s) ok[i] = 1; //完整的窗口
if (i < s && tot == i) ok[i] = 1; //在左端不完整的窗口
if (i > n && tot == n+s-i) ok[i] = 1; //在右端不完整的窗口
//滑动窗口后更新cnt和tot
if (i == n+s) break; //没有更多的窗口
if (x[i] != -1 && --cnt[x[i]]==0) tot--; //左端数字滑出窗口
if (x[i+s] != -1 && cnt[x[i+s]]++==0) tot++; //右端数字滑进窗口
}
//检验每种可能的答案
int ans = 0;
for(int i = 0; i < s; i++) {
int valid = 1;
for (int j = i; j < n+s+1; j += s)
if(!ok[j]) valid = 0;;
if(valid) ans++;
}
if(ans == n+1) ans = s; //特殊情况
cout << ans << "\n";
}
return 0;
}