BZOJ3448 : [Usaco2014 Feb]Auto-complete
RE了几十发,实在没办法了…只好向管理员要数据,然后发现数据规模与题目描述不符…
建立Trie并求出DFS序,同时根据DFS序确定字典序
然后每次询问相当于询问子树第k小,用主席树维护,注意压缩内存
时间复杂度O(L+nlogw),L为所有串长度之和
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | #include<cstdio> #include<cstring> const int N=100010,T=2100000,M=2000010; int n,q,i,k,v[T],st[T],en[T],tot,dfn,now,root[T],l[M],r[M],cnt,val[M],a[N],b[N],seq[T]; int g[T],nxt[T],to[T],ed; char s[T],ch[T],w[T]; inline void addedge( int x, int y, int z){to[++ed]=y,w[ed]=z;nxt[ed]=g[x];g[x]=ed;} inline int son( int x, int y){ for ( int i=g[x];i;i=nxt[i]) if (w[i]==y) return to[i]; return 0; } inline void ins( int p){ for ( int x=0,i=0,j=std:: strlen (s),w;i<j;i++){ if (!son(x,w=s[i]- 'a' ))addedge(x,++tot,w); x=son(x,w); if (i==j-1)v[x]=p; } } void dfs( int x){ if (v[x])a[v[x]]=++now; seq[st[x]=++dfn]=a[v[x]]; for ( int i=0;i<26;i++) if (son(x,i))dfs(son(x,i)); en[x]=dfn; } int add( int x, int a, int b, int c){ int y=++cnt; val[y]=val[x]+1; if (a==b) return y; int mid=(a+b)>>1; if (c<=mid)l[y]=add(l[x],a,mid,c),r[y]=r[x]; else l[y]=l[x],r[y]=add(r[x],mid+1,b,c); return y; } inline int ask( int k){ int x=0,i=0,j=std:: strlen (ch),w,y,c=1,d=n,mid; for (;i<j;x=son(x,w),i++) if (!son(x,w=ch[i]- 'a' )) return -1; y=root[st[x]-1],x=root[en[x]]; if (val[x]-val[y]<k) return -1; while (c<d){ mid=(c+d)>>1,j=val[l[x]]-val[l[y]]; if (k<=j)d=mid,x=l[x],y=l[y]; else k-=j,c=mid+1,x=r[x],y=r[y]; } return b[c]; } int main(){ scanf ( "%d%d" ,&n,&q); for (i=1;i<=n;i++) scanf ( "%s" ,s),ins(i); for (dfs(0),i=1;i<=n;i++)b[a[i]]=i; for (i=1;i<=dfn;i++)root[i]=seq[i]?add(root[i-1],1,n,seq[i]):root[i-1]; while (q--) scanf ( "%d%s" ,&k,ch), printf ( "%d\n" ,ask(k)); return 0; } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术