KMP+hash hdu3746 Cyclic Nacklace

传送门:点击打开链接

题意:已知原串,在首或者尾加上一些字符后,变成至少有一个循环节循环2次变成新串

思路:我们能很容易的发现,在首添加字母和在尾添加字母效果是一样的,所以我们只考虑在末尾添加

首先我们都知道,KMP可以用来求前缀中的最长循环节长度。知道了这个有什么用呢?

我们枚举所有的前缀,然后取得循环节的长度w,与此时后面剩下的字符串的长度t去比较

如果后面剩下的字符串等于原字符串的前缀,那么就更新一次答案w-t取最小

利用hash记录前缀和后缀,能快速完成后面那一步

#include <map>
#include <set>
#include <cmath>
#include <ctime>
#include <stack>
#include <queue>
#include <cstdio>
#include <cctype>
#include <bitset>
#include <string>
#include <vector>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <functional>
#define fuck(x) cout << "[" << x << "]"
#define FIN freopen("input.txt", "r", stdin)
#define FOUT freopen("output.txt", "w+", stdout)
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int, int> PII;

const int MX = 5e5 + 5;
const int INF = 0x3f3f3f3f;
const int se = 131;

char S[MX];
int Next[MX];
void GetNext(char S[], int n) {
    Next[0] = 0;
    for(int i = 1; i < n; i++) {
        int j = Next[i - 1];
        while(j && S[i] != S[j]) j = Next[j - 1];
        Next[i] = S[i] == S[j] ? j + 1 : 0;
    }
}
int f(int p) {
    return (p + 1) % (p - Next[p] + 1) == 0 ? p - Next[p] + 1 : p + 1;
}

ULL L[MX], R[MX];
int main() {
    int T; //FIN;
    scanf("%d", &T);
    while(T--) {
        scanf("%s", S);
        int n = strlen(S);
        GetNext(S, n);

        L[0] = 0;
        for(int i = 0; i < n; i++) {
            L[i + 1] = L[i] * se + S[i];
        }
        R[n] = 0; ULL fac = 1;
        for(int i = n - 1; i >= 0; i--) {
            R[i] = R[i + 1] + fac * S[i];
            fac *= se;
        }

        int ans = INF;
        for(int i = 0; i < n; i++) {
            int w = f(i), res = n - i - 1;
            if(w < res) continue;
            if(R[n - res] == L[res]) {
                ans = min(ans, w - res);
            }
        }
        printf("%d\n", ans);
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值