POJ 2752 Seek the Name, Seek the Fame (next數組)

題目鏈接

題意:給定若干只含小寫字母的字符串(這些字符串總長≤400000),在每個字符串中求出所有既是前綴又是後綴的子串長度。

例如:ababcababababcabab,既是前綴又是後綴的子串:ab,abab,ababcabab,ababcababababcabab。

分析:根據next數組的定義求解。注意串本身是一個,可以單獨輸出。

#include <iostream>
#include <cmath>
#include <iomanip>
#include <cstring>
#include <vector>
#include <string>
#include <map>
#include <queue>
#include <stack>
#include <set>
#include <cstdio>
#include <algorithm>
#define INF 0x3f3f3f3f
#define PI acos(-1)
const double eps=1e-6;
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
const int mod=1e9+7;
const int maxn=4e5+10;

int nx[maxn];
void getnx(string x){
	int m=x.size();
	int i,j;
	j=nx[0]=-1;
	i=0;
	while (i<m){
		while (-1!=j && x[i]!=x[j]) j=nx[j];
		//if (x[++i]==x[++j]) nx[i]=nx[j];
		nx[++i]=++j;
	}
}
/*int kmp(string s, string t) { 
	int n=s.size();
	int m=t.size();
	int i=0,j=0;
	getnx(t);
	while (i<n && j<m) {
		while (-1!=j && s[i]!=t[j]) j=nx[j];
		i++;
		j++;
	}
	if (j==m)
		return i-j;
	else return -1;
}*/

int main() {
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	string s;
	while (cin>>s){		
		memset(nx,0,sizeof(nx)); 
		getnx(s);
		vector <int> ans;
		int len=s.size();
		while (nx[len]){
			ans.push_back(nx[len]);
			len=nx[len];
		}
		for (int i=ans.size()-1; i>=0; i--)
			cout<<ans[i]<<" ";
		cout<<s.size();
		cout<<endl;
	}
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章