您的位置:首页 > 其它

Seek the Name, Seek the Fame POJ - 2752 (KMP next数组 的 其他用法)

2017-08-21 10:21 666 查看
The little cat is so famous, that many couples tramp over hill and dale to Byteland, and asked the little cat to give names to their newly-born babies. They seek the name, and at the same time seek the fame. In order to escape from such boring job, the innovative little cat works out an easy but fantastic algorithm:

Step1. Connect the father’s name and the mother’s name, to a new string S.

Step2. Find a proper prefix-suffix string of S (which is not only the prefix, but also the suffix of S).

Example: Father=’ala’, Mother=’la’, we have S = ‘ala’+’la’ = ‘alala’. Potential prefix-suffix strings of S are {‘a’, ‘ala’, ‘alala’}. Given the string S, could you help the little cat to write a program to calculate the length of possible prefix-suffix strings of S? (He might thank you by giving your baby a name:)

Input

The input contains a number of test cases. Each test case occupies a single line that contains the string S described above.

Restrictions: Only lowercase letters may appear in the input. 1 <= Length of S <= 400000.

Output

For each test case, output a single line with integer numbers in increasing order, denoting the possible length of the new baby’s name.

Sample Input

ababcababababcabab

aaaaa

Sample Output

2 4 9 18

1 2 3 4 5

这道题的 大概意思 就是 给你一个 字符串,求 前缀,和 后缀 相同 的 字符串的 长度, 而且 要求 长度 从 小到大 输出, 这里先 说一下 前缀 与 真前缀,后缀与真后缀, 所谓真前缀就是,不包含 字符串的 最后一个 字符,而前缀 最长 可以 等于 字符串本身, 后缀 与 真后缀 也是如此,真后缀 不包含 字符串 的第一个字符,这道题 说的是 前缀 ,后缀,说明 可以 等于 字符串本身,结合一下样例自然就明白啦。这道题 呢 教大家 next 数组 的 一个新的 用法,我自己也是刚刚学会,有什么 不对的 地方 欢迎大家 来 指出错误!! 思路 比较简单 ,基本上就是 KMP 的模版 只有 输出 用到啦 next 数组,其他的 都一样,所以就不写 思路啦,相信大家肯定能够 看懂的!!

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <stack>
using namespace std;

void GetNext(char *p, int *next)//  该函数 没有发生 变化 与 模版函数 相同
{

a6fd
int p_len = strlen(p);
int i = 0;
int j = -1;
next[0] = -1;
while(i < p_len)
{
if(j == -1 || p[i] == p[j])
{
i++;
j++;
next[i] = j;
}
else
j = next[j];
}
}

int main()
{
static char p[400010];// 这里的 static 是将 数组 定义在 静态 存储区啦 与 将数组 定义在 main 函数 外部 的作用是一样的

while(gets(p))
{
stack<int> s;
static int next[400010];

GetNext(p, next);

int j = strlen(p);
while(j > 0)
{
s.push(j);
j = next[j];
}

while(!s.empty())
{
printf("%d ", s.top());
s.pop();
}
cout<<endl;
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: