HDU - 3746 (kmp+最小循环节)

题目链接

http://acm.hdu.edu.cn/showproblem.php?pid=3746

题意

给你一个字符串,问你要使得这个字符串的最小循环节出现次数大于等于2,需要在前面或者后面添加多少字符。

思路

先用kmp求出最小循环节的长度,如果不能整除字符串长度,则余数就是需要添加的字符,如果能够整除,特判一下最小循环节出现次数为1的情况就好。

代码

#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#include<cmath>
#include<map>
#include<algorithm>
#include<string>
#include<string.h>
#include<set>
#include<queue>
#include<stack>
#include<functional>
using std::pair;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> PII;
typedef pair<PII,int> PPI;
typedef pair<ll,int> PLI;
const double PI=acos(-1);
const int maxn = 1e6+10;
const int maxm = 1e5 + 10;
const int mod = 1e9+7;
const int INF = 0x3f3f3f3f;
using namespace std;
int nex[maxm];
char s[maxn],t[maxm];
void getnext()
{
    nex[0]=-1;
    int j=0,k=-1;
    int len=strlen(t);
    while(j<len)
    {
        if(k==-1||t[j]==t[k]) nex[++j]=++k;
        else k=nex[k];
    }
}

int kmp()
{
    getnext();
    int i=0,j=0;
    int ans=0;
    int lens=strlen(s),lent=strlen(t);
    while(i<lens)
    {
        if(j==-1||s[i]==t[j]) i++,j++;
        else j=nex[j];
        if(j==lent)
        {
            ans++;
            //cout<<nex[j]<<endl;
            j=nex[j];
        }
    }
    return ans;
}

int main()
{
   int tt;
   cin>>tt;
   while(tt--)
   {
       scanf("%s",t);
       getnext();
       int len=strlen(t);
       int l=len-nex[len];
       if(len%l||(len%l==0&&len==l))
        printf("%d\n",l-len%l);
        else printf("0\n");
   }
}

猜你喜欢

转载自blog.csdn.net/a670531899/article/details/81569722
今日推荐