the main algorithm of the code:
1, find the first repeat position of the sequence, and mark it (for that once it repeat, it can never be ok)
2,use the array named ok to mark whether the sequence from i to i+s-1 is never repeat
3,check from the position i to the end to find that if the ok[i] is always true, which means that the later word is fine(= =), if so , the position of the first word can be sure as the n-i, s0 ans++
code:
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
typedef long long int64;
const int INF = 0x3f3f3f3f;
const int MAXN = 100010;
int s, n;
int arr[MAXN];
int cnt[MAXN];
bool first[MAXN], ok[MAXN];
void init() {
memset(first, 0, sizeof(first));
memset(ok, 0, sizeof(ok));
memset(cnt, 0, sizeof(cnt));
first[0] = 1, ok[n] = 1;
int i;
for(i=0; i<s&&i<n&&!cnt[arr[i]]; i++) {
cnt[arr[i]] = 1;
first[i+1] = 1;
}
if(i==n && i<s && first[i]) {
while(i++<s) first[i] = 1;
}
memset(cnt, 0, sizeof(cnt));
ok[n] = 1;
int count = 0;
for(int i=n-1; i>=0; --i){
if(cnt[arr[i]]++ == 0) {
//cnt[arr[i]]++;//it is wrong
count++;
}
if(count == s || n-i<s&&n-i==count){
ok[i] = true;
}
if(i+s-1<n){
if(--cnt[arr[i+s-1]] == 0){ //the word is out of consider
--count;
}
}
}
}
bool check(int st) {
while(st<n) {
if(!ok[st]) return false;
st += s;
}
return true;
}
int main() {
int kase;
scanf("%d", &kase);
while(kase--) {
scanf("%d%d", &s, &n);
for(int i=0; i<n; i++) {
scanf("%d",&arr[i]);
}
init();
int ans = 0;
for(int i=0; i<s; i++) //give out all the possible position
if(first[i] && check(i)) {
++ans;
}
printf("%d\n", ans);
}
return 0;
}
本文详细阐述了一种用于寻找序列中重复位置的算法。通过使用标记数组和遍历序列,该算法能够有效识别并标记重复元素。进一步地,通过检查序列的后续部分,算法能确定重复序列的起始位置,从而解决实际问题。
1216

被折叠的 条评论
为什么被折叠?



