HDU3746
本题题意为添加最少的字符使原字符串变成周期至少为2的循环字符串
用到模板里所说的,长度为len的字符串的最小循环节为len-next[len],求出最小循环节,算出最后应该补充多少就结束了。
求最小循环节的证明法请看此链接KMP求字符串最小循环节
HDU3746代码
#include<stdio.h>
#include<iostream>
#include<string.h>
using namespace std ;
const int maxn = 1e6+5;
int Next[maxn];
char str[maxn];
char mo[maxn];
int n1,n2;
void GetNext()
{
int i=0,j=-1;
while(i<n2)
{
if(j==-1||mo[i]==mo[j]) {++i,++j,Next[i]=j;}
else j=Next[j];
}
return ;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%s",mo);
n2=strlen(mo);
Next[0]=-1;
GetNext();
int tmp=n2-Next[n2];
if(n2%tmp==0&&n2!=tmp)
{
printf("0\n");
}
else
{
printf("%d\n",tmp-n2%tmp);
}
}
return 0;
}