Cyclic Nacklace HDU - 3746 (kmp next数组应用)

题目大意

给出字符串,寻找最小要补全的字符个数,使得字符串是两次的循环

解法

通过寻找规律,我们又发现了len-next[len]又派上了用场

①如果next[len]是0,说明最大前缀后缀和为0,那么这个串里面没有什么重复的那种部分,也就是输出len例如abcde

②如果len%(len-next[len])==0也就是说里面已经具有这种重复两次的串了,所以输出0,例如aaa

③如果上述情况都不是,那么说明这个串里面包含重复部分但是不全。那么输出的公式是(len-next[len[)-len%(len-next[len])

对于③的简单图示(存在一定的比例的问题。。。)

代码

#include <bits/stdc++.h>
using namespace std;
char a[100005];
int nex[100005];
int len;
void get()
{
  memset(nex,0,sizeof(nex));
  int j=0;
  for(int i=2;i<=len;i++)
  {
    while(j&&a[i]!=a[j+1])
    j=nex[j];
    if(a[i]==a[j+1])
    j++;
    nex[i]=j;
  }
}
int main()
{
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  int n;
  cin>>n;
  while(n--)
  {
    cin>>a+1;
    len=strlen(a+1);
    get();
    int t1=len-nex[len];
    if(nex[len]==0)
    cout<<len<<"\n";
    else if(len%t1==0)
    cout<<0<<"\n";
    else
    cout<<t1-len%t1<<"\n";
  }
}
posted @ 2018-11-30 11:33  baccano!  阅读(127)  评论(0编辑  收藏  举报