POJ 2752 Seek the Name, Seek the Fame(next数组的理解)

做此题,只要理解好next数组就行.......................

#include <cstdio>
#include <cmath>
#include <iostream>
#include <cstring>
#include <string>
#include <algorithm>
using namespace std;
char str[411111],tmp[411111];
int next[411111],ans[411111]; void getnext(char *t) {
int i=0,j=-1;
int len = strlen(t);
next[0] = -1;
while(i < len) {
if(t[i] == t[j] || j == -1) {
i ++;
j ++;
next[i] = j;
} else j = next[j];
}
}
/*
int kmp(char *s,char *t) {
int lens = strlen(s);
int lena = strlen(t);
int i=0,j=0;
while(i < lens && j < lena) {
if(s[i] == t[j] || j == -1) {
i++;
j++;
} else j = next[j];
}
if(j < lena) return -1;
return i - lena;
}
*/
int main() {
while(scanf("%s",str) != EOF) {
strcpy(tmp,str);
int len = strlen(str);
int cnt = 0;
getnext(str);
int j = next[len];
ans[cnt++] = j;
while(j > 1) {
ans[cnt++] = next[j];
j = next[j];
}
for(int i=cnt-1; i>=0; i--) {
if(ans[i] != 0)
printf("%d ",ans[i]);
}
printf("%d\n",len);
}
return 0;
}
上一篇:C语言库函数探究


下一篇:LDA(latent dirichlet allocation)的应用