Seek the Name, Seek the Fame 【POJ - 2752】【KMP算法next[]的用法拓展】

KMP算法的在线答疑哦

题目链接


给你一个字符串,问你他的前缀子串,就是说例如有一组字符串“asdasdasd”可以推出->“asdasd”->“asd”,其实就是问你next[]数组向前回溯过程所能遍历的值,然后倒过来输出即可。


#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
#include <limits>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#define lowbit(x) ( x&(-x) )
#define pi 3.141592653589793
#define e 2.718281828459045
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
const int maxN=400005;
char s[maxN];
int lens, nex[maxN];
void cal_next()
{
    nex[0] = nex[1] = 0;
    int k = 0;
    for(int i=2; i<=lens; i++)
    {
        while(k>0 && s[k+1]!=s[i])
        {
            k=nex[k];
        }
        if(s[k+1] == s[i]) k++;
        nex[i] = k;
    }
}
void dfs(int x)
{
    if(nex[x]>0)
    {
        dfs(nex[x]);
        printf("%d ", nex[x]);
    }
}
int main()
{
    while(scanf("%s", s+1)!=EOF)
    {
        lens=(int)strlen(s+1);
        cal_next();
        dfs(lens);
        printf("%d\n", lens);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41730082/article/details/83413383