NC22395. Philosophical … Balance
描述
输入描述
The first line contains one integer , the number of test cases. Then T test cases follow.
Each test case contains a string s of length , consisting of only lowercase letters, the secret key.
It is guaranteed that the sum of n in all test cases is at most .
输出描述
Output T lines; each line contains a decimal number, the answer to that test case.
Your answer is considered correct if the absolute or relative error doesn't exceed .
示例1
输入:
3 aba aaaaaaaaaaa abcd
输出:
0.66666666667 1 0.48
C++11(clang++ 3.9) 解法, 执行用时: 341ms, 内存消耗: 120164K, 提交时间: 2020-03-17 11:14:01
#include<bits/stdc++.h> using namespace std; typedef long double ld; const int maxn=1000000; char s[maxn+10]; int n,t; namespace sam { const int maxc=maxn*2; ld f[maxc+10]; int ch[maxc+10][26],fa[maxc+10],maxl[maxc+10],np=1,ndcnt=1; bool is[maxc+10]; vector<int> g[maxc+10]; void init() { for(int i=1;i<=ndcnt;++i) { memset(ch[i],0,sizeof ch[i]); fa[i]=maxl[i]=is[i]=0; f[i]=0; g[i].clear(); } np=ndcnt=1; } void add(int c) { int p=np; np=++ndcnt; maxl[np]=maxl[p]+1; is[np]=1; for(;p&&!ch[p][c];p=fa[p]) ch[p][c]=np; if(p) { int q=ch[p][c]; if(maxl[p]+1==maxl[q]) fa[np]=q; else { int nq=++ndcnt; fa[nq]=fa[q]; fa[q]=fa[np]=nq; maxl[nq]=maxl[p]+1; for(int i=0;i<26;++i) ch[nq][i]=ch[q][i]; for(;ch[p][c]==q;p=fa[p]) ch[p][c]=nq; } } else fa[np]=1; } void dfs(int p) { if(is[p]) { f[p]=maxl[p]; return; } ld sum=0; for(int i=0;i<(int)g[p].size();++i) { int e=g[p][i]; dfs(e); sum+=1./(f[e]-maxl[p]); } int c=g[p][0]; f[p]=maxl[p]+1./(f[c]-maxl[p])/sum*(f[c]-maxl[p]); } void build() { for(int i=2;i<=ndcnt;++i) g[fa[i]].push_back(i); dfs(1); } } int main() { scanf("%d",&t); while(t--) { sam::init(); scanf("%s",s+1); n=strlen(s+1); reverse(s+1,s+n+1); for(int i=1;i<=n;++i) sam::add(s[i]-'a'); sam::build(); printf("%.10Lf\n",sam::f[1]); } }