计蒜客习题:重复的密文


问题描述

蒜头君收到了一串密文,但是由于接收器坏了,他不停的重复接收,终于,蒜头君把插头拔了,机器停止了,但是蒜头君已经收到了一个很长字符串,它是由某个原始串不停的重复形成了,因为断电,最后一遍也不一定是完整的。蒜头君现在想知道这个原始串的最短可能长度是多少。
输入格式
第一行输入一个正整数 L(1< L≤1e6),表示这个字符串的长度。
第二行输入一个字符串,全部由小写字母组成。
输出格式
答案输出,输出最短的可能长度。
样例输入
8
cabcabca
样例输出
3


AC代码


#include <iostream>
#include <cstdio>
using namespace std;
const int MAXN=1e6+10;
char P[MAXN];
int fail[MAXN];

void getFail() {
    int match = -1;
    fail[0] = -1;
    for (int i = 1; P[i]; ++i) {
        while (match >= 0 && P[match + 1] != P[i]) {
            match = fail[match];
        }
        if (P[match + 1] == P[i]) {
            match++;
        }
        fail[i] = match;
    }
}

int main(){
    int n;
    cin>>n;
    char tmp;
    int cnt=0;
    for(int i=0;i<n;i++){
        cin>>P[i];
    }
    getFail();
    cout<<n-1-fail[n-1];
    return 0;
}

猜你喜欢

转载自blog.csdn.net/liukairui/article/details/80622350