[BZOJ1355] [Baltic2009]Radio Transmission

[Baltic2009]Radio Transmission

Description
给你一个字符串,它是由某个字符串不断自我连接形成的。 但是这个字符串是不确定的,现在只想知道它的最短长度是多少.
Input
第一行给出字符串的长度,1 < L ≤ 1,000,000. 第二行给出一个字符串,全由小写字母组成.
Output
输出最短的长度
Sample Input
8
cabcabca
Sample Output
3
HINT
对于样例,我们可以利用”abc”不断自我连接得到”abcabcabc”,读入的cabcabca,是它的子串
Source

Solution :
假设一个串是一个小串循环得到的,那么这个串从第二个循环节开始到结束的这个后缀一定是和开头的前缀匹配的。
所以答案是n-fail[n]

Code :

#include <bits/stdc++.h>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/hash_policy.hpp>
#include <ext/pb_ds/priority_queue.hpp>
#include <ext/pb_ds/assoc_container.hpp>
using namespace std;

typedef long long ll;
typedef pair<int, int> PII;
#define rep(i, l, r) for (int i = (l); i <= (r); i++)
#define per(i, r, l) for (int i = (r); i >= (l); i--)
#define fst first
#define sec second
#define MS(_) memset(_, 0, sizeof(_))
#define PB push_back
#define MP make_pair

template<typename _T> inline void read(_T &x){
    x = 0; bool f = 1; char ch = getchar();
    while (!isdigit(ch)) {if (ch == '-') f = 0; ch = getchar();}
    while (isdigit(ch)) {x = x * 10 + ch - '0'; ch = getchar();}
    x = f ? x : -x;
}

int len;
char st[1111111];
int fail[1111111];

int main(){
    read(len);
    scanf("%s", st+1);

    for(int i = 2, j = 0; i <= len; i++){
        while (st[j + 1] != st[i] && j) j = fail[j];
        if (st[j + 1] == st[i]) j++;
        fail[i] = j;           
    }

    printf("%d\n", len - fail[len]);

    return 0;    
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值