Cyclic Nacklace ---hdu3746(循环节,kmp)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3746

给你一个字符串,让你在后面加尽量少的字符,使得这个字符串成为一个重复串。

abca---添加bc,成为abcabc

abcd---添加abcd,成为abcdabcd

aa---无需添加

经典的求最小循环节。

首先给出结论:一个字符串的最小循环节为:len-next[len]

#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;

const int N = 1e5+7;

char s[N];
int Next[N], n;

void GetNext()
{
    int i=0, j=-1;
    Next[0] = -1;
    while(i<n)
    {
        if(j==-1 || s[i] == s[j])
            Next[++i] = ++j;
        else
            j=Next[j];
    }
}
int main()
{
    int ans, T;
    scanf("%d", &T);
    while(T--)
    {
        scanf("%s", s);
        n = strlen(s);
        GetNext();
        ans = n - Next[n];
        if(Next[n] == 0)
        {
            printf("%d
", n);
            continue;
        }
        if(n%ans==0)///判断是否已经不需要添加了;
            ans = 0;
        else
            ans = ans - Next[n] % ans;
        printf("%d
", ans);
    }
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/zhengguiping--9876/p/4835228.html