POJ2752 KMP next数组的活用

来源:互联网 发布:人工智能包括机器人吗 编辑:程序博客网 时间:2024/06/07 21:12

题意 给你一个串,找出它的所有子串,这些子串要求既是原串的前缀,也是原串的后缀

思路 考察next数组的理解,对串中任意位置i来说,0~(next[i]-1)这个子串,是原串的一个前缀子串,同时它和(i - next[i])~(i-1)这个子串是相等的。因此令i = n,则通过next[n]可以找到一个满足题目要求的最长子串(除了原串外),然后迭代的去找这个最长子串满足条件的子串~

注意:next[n]在普通区匹配串时用处不大,但在利用next数组性质时很有用~

#include <stdio.h>#include <string.h>#include <stack> using namespace std;const int maxn = 400005;char str[maxn];int next[maxn];int n;stack<int> sta; void getNext(){next[0] = 0;next[1] = 0;int i,j;for(i=1;i<n;i++){j = next[i];while(j && str[j] != str[i])j = next[j];if(str[i] == str[j])next[i+1] = j+1;elsenext[i+1] = 0;}}int main(){while(gets(str)){n = strlen(str);getNext();sta.push(n);while(next[n] > 0){n = next[n];sta.push(n);}while(sta.size()> 1){printf("%d ",sta.top());sta.pop();}printf("%d\n",sta.top());sta.pop();}return 0;}


0 0