POJ-2752 Seek the Name, Seek the Fame

一道简单的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;
}

你可能感兴趣的:(POJ-2752 Seek the Name, Seek the Fame)