Many Equal Substrings-(KMP)-Codeforces Round #506 (Div. 3) A题

该博客介绍利用KMP算法中的next数组求循环节的思路,具体过程可查看代码。KMP算法是信息技术领域常用算法,next数组在其中有重要作用,通过它可实现循环节的求解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

思路:
利用KMP算法中的next数组,求循环节。
具体过程看代码。

AC code:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<string>
#include<cstring>

using namespace std;
const int maxn = 1e5 + 10;
int nex[maxn];
string str1,str2;
int n = 0,k = 0;
int ans = 0;
void make_nex(){
    int j = 0,k = -1;
    nex[0] = -1;
    int len2 = str2.size();
    while(j < len2){//是j < m而不是m-1,虽然j <m-1也AC了,j < m不用担心越界 
        if(k == -1 || str2[k] == str2[j]){
            if(str2[k+1] == str2[j+1]){
                nex[j+1] = nex[k+1];
                ++j,++k;
            }else{
                nex[j+1] = k+1;
                ++j,++k;
            }
        }else{
            k = nex[k];
        }
    }   
}

int main(){

    while(cin >> n >> k){
        cin >> str2;
        memset(nex,0,sizeof(nex));
        make_nex();
        str1 = str2;

        for(int j = 0;j < k - 1;++j){
            for(int i = nex[n];i < n;++i){
                str1 += str2[i];
            }
        }
        cout << str1 << endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值