【SPOJ】8222. Substrings(后缀自动机)
http://www.spoj.com/problems/NSUBSTR/
题意:给一个字符串S,令F(x)表示S的所有长度为x的子串中,出现次数的最大值。求F(1)..F(Length(S))
这题做法:
首先建立字符串的后缀自动机。
所以对于一个节点$s$,长度范围为$[Min(s), Max(s)]$,出现次数是$|Right(s)|$,那么我们用$|Right(s)|$去更新$f(Max(s))$,最后用$f(i)$更新$f(i-1)$即可。
#include <cstdio> #include <cstring> #include <cmath> #include <string> #include <iostream> #include <algorithm> #include <queue> #include <set> #include <map> using namespace std; typedef long long ll; #define rep(i, n) for(int i=0; i<(n); ++i) #define for1(i,a,n) for(int i=(a);i<=(n);++i) #define for2(i,a,n) for(int i=(a);i<(n);++i) #define for3(i,a,n) for(int i=(a);i>=(n);--i) #define for4(i,a,n) for(int i=(a);i>(n);--i) #define CC(i,a) memset(i,a,sizeof(i)) #define read(a) a=getint() #define print(a) printf("%d", a) #define dbg(x) cout << (#x) << " = " << (x) << endl #define error(x) (!(x)?puts("error"):0) #define rdm(x, i) for(int i=ihead[x]; i; i=e[i].next) inline const int getint() { int r=0, k=1; char c=getchar(); for(; c<'0'||c>'9'; c=getchar()) if(c=='-') k=-1; for(; c>='0'&&c<='9'; c=getchar()) r=r*10+c-'0'; return k*r; } struct sam { static const int N=1000005; int c[N][26], l[N], f[N], root, last, cnt; sam() { cnt=0; root=last=++cnt; } void add(int x) { int now=last, a=++cnt; last=a; l[a]=l[now]+1; for(; now && !c[now][x]; now=f[now]) c[now][x]=a; if(!now) { f[a]=root; return; } int q=c[now][x]; if(l[q]==l[now]+1) { f[a]=q; return; } int b=++cnt; memcpy(c[b], c[q], sizeof c[q]); l[b]=l[now]+1; f[b]=f[q]; f[q]=f[a]=b; for(; now && c[now][x]==q; now=f[now]) c[now][x]=b; } void build(char *s) { int len=strlen(s); rep(i, len) add(s[i]-'a'); } }a; const int N=250005; char s[N]; int f[N], r[1000005], t[N], b[1000005]; void getans(int len) { int *l=a.l, *p=a.f, cnt=a.cnt; for(int now=a.root, i=0; i<len; ++i) now=a.c[now][s[i]-'a'], ++r[now]; for1(i, 1, cnt) ++t[l[i]]; for1(i, 1, len) t[i]+=t[i-1]; for1(i, 1, cnt) b[t[l[i]]--]=i; for3(i, cnt, 1) r[p[b[i]]]+=r[b[i]]; for1(i, 1, cnt) f[l[i]]=max(f[l[i]], r[i]); for3(i, len, 1) f[i]=max(f[i+1], f[i]); for1(i, 1, len) printf("%d\n", f[i]); } int main() { scanf("%s", s); a.build(s); getans(strlen(s)); return 0; }
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
博客地址:www.cnblogs.com/iwtwiioi 本文为博主原创文章,未经博主允许不得转载。一经发现,必将追究法律责任。