题目链接
题意:给定字符串,问最少添加多少个字符串能让其循环。
分析:从KMP的next数组定义可以知道:
next[i] : 满足 x[i-k…i-1]=x[0…k-1] 的最大 k 值
(最长公共前后缀的长度)
从这题看就是 已经相等的前后缀的长度, 那么 same=len - next [len] 最小循环节的长度。
- 如果 nx[len] = 0 ,前面都没有相同前后缀,所以输出 len
- 如果 len%same = 0 ,说明整段都是循环的,所以输出 0
- 其他情况下,输出 same - len%same 就是缺的字符个数
PS:奇妙wa的原因是 关闭输出流,不能直接cout<<0
#include <iostream>
#include <cmath>
#include <iomanip>
#include <cstring>
#include <vector>
#include <string>
#include <map>
#include <queue>
#include <stack>
#include <set>
#include <cstdio>
#include <algorithm>
#define INF 0x3f3f3f3f
#define PI acos(-1)
using namespace std;
typedef long long ll;
typedef pair<string, string> P;
const int mod=1e9+7;
const int maxn=1e5+10;
int nx[maxn];
void getnx(string x){
int m=x.size();
int i,j;
j=nx[0]=-1;
i=0;
while (i<m){
if (j==-1 || x[i]==x[j]){
i++,j++;
nx[i]=j;
}
else j=nx[j];
}
}
string s;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int T;
cin>>T;
while (T--){
memset(nx,0,sizeof(nx));
cin>>s;
getnx(s);
int len=s.size();
int same=len-nx[len];
if (nx[len]==0) cout<<len<<endl;
else if (len%same==0) cout<<"0"<<endl;
else cout<<same-len%same<<endl;
}
return 0;
}