【SPOJ8222】Substrings (后缀自动机)

题意:

给一个字符串S,令F(x)表示S的所有长度为x的子串中,出现次数的最大值。

求F(1)..F(Length(S)) Length(S) <= 250000

思路:板子中st[x]定义为root到x的最多步数,可以用来更新所有长度为[1..st[x]]的答案

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 typedef long long ll;
 4 typedef unsigned int uint;
 5 typedef unsigned long long ull;
 6 typedef pair<int,int> PII;
 7 typedef pair<ll,ll> Pll;
 8 typedef vector<int> VI;
 9 typedef vector<PII> VII;
10 typedef pair<ll,int>P;
11 #define N  510000
12 #define M  151000
13 #define fi first
14 #define se second
15 #define MP make_pair
16 #define pi acos(-1)
17 #define mem(a,b) memset(a,b,sizeof(a))
18 #define rep(i,a,b) for(int i=(int)a;i<=(int)b;i++)
19 #define per(i,a,b) for(int i=(int)a;i>=(int)b;i--)
20 #define lowbit(x) x&(-x)
21 #define Rand (rand()*(1<<16)+rand())
22 #define id(x) ((x)<=B?(x):m-n/(x)+1)
23 #define ls p<<1
24 #define rs p<<1|1
25 
26 const int MOD=998244353,inv2=(MOD+1)/2;
27       double eps=1e-6;
28       ll INF=1e18;
29       ll inf=5e13;
30       int dx[4]={-1,1,0,0};
31       int dy[4]={0,0,-1,1};
32 
33 char ch[N];
34 int n,i,x,p,q,np,nq,cnt,L,st[N],c[N][26],f[N],pos[N],bl[N],to[N],b[N],sz[N],ans[N];
35 
36 int read()
37 {
38    int v=0,f=1;
39    char c=getchar();
40    while(c<48||57<c) {if(c=='-') f=-1; c=getchar();}
41    while(48<=c&&c<=57) v=(v<<3)+v+v+c-48,c=getchar();
42    return v*f;
43 }
44 
45 void add(int x)
46 {
47     p=np;
48     st[np=++cnt]=st[p]+1;
49     to[np]=i;
50     pos[i]=np;
51     while(p&&!c[p][x])
52     {
53         c[p][x]=np;
54         p=f[p];
55     }
56     if(!p) f[np]=1;
57      else if(st[p]+1==st[q=c[p][x]]) f[np]=q;
58       else
59       {
60           st[nq=++cnt]=st[p]+1;
61           memcpy(c[nq],c[q],sizeof c[q]);
62           f[nq]=f[q];
63           f[q]=f[np]=nq;
64           while(p&&c[p][x]==q)
65           {
66               c[p][x]=nq;
67               p=f[p];
68           }
69       }
70 }
71 
72 
73 int main()
74 {
75     //freopen("1.in","r",stdin);
76     //freopen("1.out","w",stdout);
77     np=cnt=1;
78     scanf("%s",ch);
79     n=strlen(ch);
80     rep(i,0,n-1) add(ch[i]-'a');
81     rep(i,1,cnt) b[st[i]]++;
82     rep(i,1,n) b[i]+=b[i-1];
83     rep(i,1,cnt) bl[b[st[i]]--]=i;
84     for(i=0,p=1;i<n;i++) sz[p=c[p][ch[i]-'a']]++;
85     for(i=cnt;i;i--) sz[f[bl[i]]]+=sz[bl[i]];
86     //rep(i,0,n-1) printf("%d ",sz[pos[i]]);
87     rep(i,1,n) ans[i]=0;
88     rep(i,1,cnt) ans[st[i]]=max(ans[st[i]],sz[i]);
89     per(i,n-1,1) ans[i]=max(ans[i],ans[i+1]);
90     rep(i,1,n) printf("%d
",ans[i]);
91     return 0;
92 }
原文地址:https://www.cnblogs.com/myx12345/p/11460908.html