您的位置:首页 > 其它

POJ-2752 Seek the Name, Seek the Fame

2016-03-08 19:53 309 查看
一道简单的KMP算法的题,只要了解KMP的原理就能解出来

#include <iostream>
#include <cstdio>
#include <algorithm>

using namespace std;

#define maxn 400005

int next[maxn];
int ans[maxn];
void kmp(string &s)
{
next[0] = -1;
int k = -1, p = 0;

while(p < s.size())
{
if(k == -1 || s[k] == s[p])
{
k++;
p++;
next[p] = k;
}
else
k = next[k];
}
}
int main()
{
//  freopen("in.txt", "r", stdin);
string s;

while(cin >> s)
{
kmp(s);
int n = 0, t = s.size();

while(next[t])
{
ans[n++] = next[t];
t = next[t];
}
for(int i = n-1; i >= 0; i--)
cout << ans[i] << " ";
cout << s.size() << endl;
}

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