原题:2018 ICPC Asia-East Continent Final Jios
想看原题解的能够去看吉老师的直播题解ide
(dllca膜你赛搬原题差评)spa
考虑题目中给出的式子的含义,实际上至关于要给串$s$的每一个后缀分配一个几率$p_i$知足$\sum\limits_{i=1}^{n}p_i=1$,而后取其中一个与其它后缀的lcp指望值最小的后缀,要作的就是求出一种最优的分配p的方案使得最后的最小值最大;code
先不考虑后缀,考虑若干个lcp为0(即没有公共前缀)的字符串如何分配最优:blog
设有$m$个串$s_1,s_2,...,s_m$,长度分别为$l_1,l_2,...,l_m$,那么取其中一个串$s_t$对答案的贡献是$p_tl_t$,最后的答案就是$min\{p_tl_t\}$;字符串
一个结论:要使答案最大,全部$p_tl_t$的值一定相等;get
若是不全相等,答案就是其中最小的那个,则必然能够经过调整$p$使得最小的那个增长一点,其余的所有减少一点,从而使答案更优;直播
因而能够列出一个方程组:string
$$\begin{cases}\sum\limits_{i=1}^{n}p_i=1 \\ p_1l_1=p_2l_2=\cdots=p_nl_n=k\end{cases}$$it
其中$k$就是答案,联立两式得:
$$k=\frac{1}{\frac{1}{l_1}+\frac{1}{l_2}+\cdots+\frac{1}{l_n}}$$
显然就能够直接求出$k$了;
回到原问题,涉及到快速求后缀的lcp容易想到先构造出后缀树,因为后缀树本质上仍是一棵trie树,所以一个节点全部的后继节点以及向下的子树所表示的字符串在这个点向后的部分都是没有公共前缀的,因此能够用上面的方法来处理;
注意到其实某一个节点子树中的问题是整个后缀树上问题彻底等价的子问题,所以能够在后缀树上dfs,父节点直接加上子树的答案继续合并便可;
dfs的时候注意若是一个节点自己已是原串某一个后缀的尾节点那么它的后继节点确定没有贡献,直接返回0便可;
因而就作完了,讲了这么多代码仍是很短的!
1 #include<algorithm>
2 #include<iostream>
3 #include<cstring>
4 #include<cstdio>
5 #include<cmath>
6 #include<queue>
7 #define inf 2147483647
8 #define eps 1e-9
9 using namespace std; 10 typedef long long ll; 11 typedef double db; 12 struct edge{ 13 int v,next; 14 }a[1000001]; 15 int t,n,tot,last,rt,tote,head[1000001],son[1000001][26],mx[1000001],fa[1000001],isp[1000001]; 16 char s[200001]; 17 void add(int u,int v){ 18 a[++tote].v=v; 19 a[tote].next=head[u]; 20 head[u]=tote; 21 } 22 void extend(int ch){ 23 int p=last,np=++tot; 24 mx[np]=mx[p]+1; 25 for(;p&&!son[p][ch];p=fa[p])son[p][ch]=np; 26 if(!p)fa[np]=rt; 27 else{ 28 int q=son[p][ch]; 29 if(mx[q]==mx[p]+1)fa[np]=q; 30 else{ 31 int nq=++tot; 32 mx[nq]=mx[p]+1; 33 memcpy(son[nq],son[q],sizeof(son[q])); 34 fa[nq]=fa[q]; 35 fa[q]=fa[np]=nq; 36 for(;p&&son[p][ch]==q;p=fa[p])son[p][ch]=nq; 37 } 38 } 39 isp[np]=true; 40 last=np; 41 } 42 db dfs(int u){ 43 if(isp[u])return 0; 44 db ret=0; 45 for(int tmp=head[u];tmp!=-1;tmp=a[tmp].next){ 46 int v=a[tmp].v; 47 ret+=1.0/(dfs(v)+mx[v]-mx[u]); 48 } 49 return 1.0/ret; 50 } 51 int main(){ 52 memset(head,-1,sizeof(head)); 53 scanf("%d",&t); 54 while(t--){ 55 scanf("%s",s); 56 n=strlen(s); 57 rt=last=++tot; 58 for(int i=n-1;i>=0;i--){ 59 extend(s[i]-'a'); 60 } 61 for(int i=rt+1;i<=tot;i++){ 62 add(fa[i],i); 63 } 64 printf("%.10lf\n",dfs(rt)); 65 } 66 return 0; 67 }