Seek the Name, Seek the Fame 【POJ
阿新 • • 發佈:2018-12-17
題目連結
給你一個字串,問你他的字首子串,就是說例如有一組字串“asdasdasd”可以推出->“asdasd”->“asd”,其實就是問你next[]陣列向前回溯過程所能遍歷的值,然後倒過來輸出即可。
#include <iostream> #include <cstdio> #include <cmath> #include <string> #include <cstring> #include <algorithm> #include <limits> #include <vector> #include <stack> #include <queue> #include <set> #include <map> #define lowbit(x) ( x&(-x) ) #define pi 3.141592653589793 #define e 2.718281828459045 using namespace std; typedef unsigned long long ull; typedef long long ll; const int maxN=400005; char s[maxN]; int lens, nex[maxN]; void cal_next() { nex[0] = nex[1] = 0; int k = 0; for(int i=2; i<=lens; i++) { while(k>0 && s[k+1]!=s[i]) { k=nex[k]; } if(s[k+1] == s[i]) k++; nex[i] = k; } } void dfs(int x) { if(nex[x]>0) { dfs(nex[x]); printf("%d ", nex[x]); } } int main() { while(scanf("%s", s+1)!=EOF) { lens=(int)strlen(s+1); cal_next(); dfs(lens); printf("%d\n", lens); } return 0; }