官方题解(讲的非常详细)
This task is to determine whether a string is in the form of ABABA... ABA for each prefixes of a given string S
For a prefix P, let's split it into some blocks, just like P = SSSS... SSSST, which T is a prefix of S. Obviously, if we use KMP algorithm, we can do it in linear time, and the length of S will be minimal. There are only two cases : T = S, T ≠ S.
- T = S. When T = S, P = SSS... S. Assume that S appears R times. Consider "ABABAB....ABABA", the last A must be a suffix of P, and it must be like SS... S, so A will be like SS... SS, and so will B. By greedy algorithm, the length of A will be minimal, so it will be SSS... S, where S appears
times. And B will be SSS... S, where S appears
times. So we just need to check whether
.
- T ≠ S . When T ≠ S, the strategy is similar to T = S. A will be like "SS...ST", and its length will be minimal. At last we just need to check whether
.
The total time complexity is O(n).
AC代码
#include <queue>
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
using namespace std;
const int MAX = 1000010;
int n, k;
char s[MAX];
int next[MAX];
void make_next(){
int i = 0, j = -1;
next[0] = -1;
while(i < n){
if(j == -1 || s[i] == s[j]){
i++, j++;
next[i] = j;
}
else j = next[j];
}
}
int main(){
scanf("%d%d", &n, &k);
scanf("%s", s);
make_next();
for(int i=1; i<=n; i++){
int cur = i - next[i];
int L = i % cur;
int cnt = i / cur;
if(L == 0){
if(cnt / k - cnt % k >= 0) printf("1");
else printf("0");
}
else{
if(cnt / k - cnt % k > 0) printf("1");
else printf("0");
}
}
puts("");
}