poj2752

kmp的变形,kmp算法是先将某穿和自身匹配,写出fail数组。我们只需要这个fail数组,它的最后一位存储了我们所要求的答案中的最大长度。然后每次利用fail数组向前跳转就可以得到所有答案。

View Code
#include <iostream>
#include
<cstdio>
#include
<cstdlib>
#include
<cstring>
#include
<stack>
using namespace std;

#define maxn 400005

char s[maxn];
int fail[maxn];

void kmp(char* pat)
{
int i, k;

memset(fail,
-1, sizeof(fail));
for (i = 1; pat[i]; ++i)
{
for (k=fail[i-1]; k>=0 && pat[i]!=pat[k+1];
k
=fail[k]);
if (pat[k + 1] == pat[i]) fail[i] = k + 1;
}
}

int main()
{
//freopen("D:\\t.txt", "r", stdin);
while (scanf("%s", s) != EOF)
{
kmp(s);
int temp = strlen(s) - 1;
stack
<int> stk;
while (temp != -1)
{
stk.push(temp
+ 1);
temp
= fail[temp];
}
printf(
"%d", stk.top());
stk.pop();
while (!stk.empty())
{
printf(
" %d", stk.top());
stk.pop();
}
printf(
"\n");
}
return 0;
}
原文地址:https://www.cnblogs.com/rainydays/p/2007166.html