1. 程式人生 > >NSUBSTR Substrings

NSUBSTR Substrings

You are given a string S which consists of 250000 lowercase latin letters at most. We define F(x) as the maximal number of times that some string with length x appears in S. For example for string 'ababa' F(3) will be 2 because there is a string 'aba' that occurs twice. Your task is to output F(i) for every i so that 1<=i<=|S|.

Input

String S consists of at most 250000 lowercase latin letters.

Output

Output |S| lines. On the i-th line output F(i).

Example

Input:
ababa

Output:
3
2
2
1
1

題解:SAM模板題。

程式碼:

#include<cstdio>
#include<vector>
#include<cstring>
#include<algorithm>
 
using namespace std;
 
typedef long long LL;
 
const int MAXN = 1000005;
 
typedef struct Node
{
	int len, pre;//pre:對應圖片中的綠線(一個節點顯然最多隻有一條綠線)
	int Next[26];//Next[]:對應圖片中的藍線
}Node;
 
Node tre[MAXN*2];
 
vector<int> G[MAXN*2];//用於建Suffix Links樹 
int cnt, last, siz[MAXN*2], ans[MAXN*2];
char str[MAXN];
 
void Insert(char ch)
{
	int p, q, now, rev;
	p = last, now = cnt++;
	tre[now].len = tre[last].len+1;
	siz[now]++;		//如果節點u包含子串S[1..i],那麼滿足|siz(u)| = ∑|siz(son(u))|+1,這裡先加上那個1,這樣的話對於SL樹就可以直接求和了
	while(p!=-1 && tre[p].Next[ch-'a']==0)	//每次跳到當前最長且siz集合與當前不同的字尾上,對應圖片中的綠線回退(例如7→8→5→S)
	{
		tre[p].Next[ch-'a'] = now;		//tran(st[p], ch)=now,對應圖片中的藍線連線
		p = tre[p].pre;
	}
	if(p==-1)
		tre[now].pre = 0;		//情況①,遞迴到了初始節點S(空子串)(例如圖片中的9號節點pre[9]=0)
	else			//如果中途某個子串tran(st[p], ch)已經存在
	{
		q = tre[p].Next[ch-'a'];
		if(tre[q].len==tre[p].len+1)		//情況②:節點q的最長子串剛好就是節點p的最長子串+S[i],也就是len[q] = len[p]+1
			tre[now].pre = q;
		else						//情況③
		{
			rev = cnt++;
			tre[rev] = tre[q];
			tre[rev].len = tre[p].len+1;	//這三行就是對Suffix Links內向樹的插點操作
			tre[q].pre = tre[now].pre = rev;
			while(p!=-1 && tre[p].Next[ch-'a']==q)
			{
				tre[p].Next[ch-'a'] = rev;
				p = tre[p].pre;
			}
		}
	}
	last = now;
}
 
void SechSL(int u)		//求出所有節點的|endpos()|
{
	int v;
	for(int i=0 ; i<G[u].size() ; ++i)
	{
		v = G[u][i];
		SechSL(v);
		siz[u] += siz[v];
	}
	ans[tre[u].len] = max(ans[tre[u].len], siz[u]);
}
 
inline void Init()
{
	cnt = last = 0;
	memset(tre, 0, sizeof(tre));
	for(int i=0 ; i<MAXN*2 ; ++i)G[i].clear();
	tre[cnt++].pre = -1;
}
 
int main()
{
	int n;
	scanf("%s", str+1);
	n = strlen(str+1);
	Init();
	for(int i=1 ; i<=n ; ++i)Insert(str[i]);
	for(int i=1 ; i<=cnt-1 ; ++i)G[tre[i].pre].push_back(i);//建樹 
	SechSL(0);
	/*---------------------------
	LL ans = 0;
	for(i=1;i<=cnt-1;i++)
		ans += tre[i].len-tre[tre[i].pre].len;	//求出有多少個本質不同的子串
	-----------------------------*/
	for(int i=n ; i>=1 ; i--)
		ans[i] = max(ans[i], ans[i+1]);
	for(int i=1 ; i<=n ; ++i)
		printf("%d\n", ans[i]);
		
	return 0;
}