题解:P15725 [JAG 2023 Summer Camp #3] LCP Queries
对
进行一些预处理,只需要快速求
时间复杂度 std::unordered_map 等数据结构的单次查询时间复杂度。
:::success[点击查看参考代码]
#include<bits/stdc++.h>
#define TIME chrono::duration_cast<chrono::milliseconds>(chrono::high_resolution_clock::now().time_since_epoch()).count()
#define rep(i,l,r) for(int qwp=(r),i=(l);i<=qwp;i++)
#define per(i,r,l) for(int qwp=(l),i=(r);i>=qwp;i--)
#define pb push_back
#define rsz resize
#define SZ(x) (int)((x).size())
#define umap unordered_map
using namespace std;
namespace c0dE1ng{
typedef unsigned long long ll;
typedef vector<int> arr;
constexpr int N=2e5+5;
constexpr int S=26;
namespace HASH{
constexpr ll m1=1e9+7,p1=1145141;
constexpr ll m2=1e9+9,p2=1333331;
mt19937_64 rng(TIME);ll rg1[S],rg2[S],pw1[N],pw2[N];
inline void Init(){rep(i,0,S-1)rg1[i]=rng()%p1,rg2[i]=rng()%p2;pw1[0]=pw2[0]=1;rep(i,1,N-5)pw1[i]=pw1[i-1]*p1%m1,pw2[i]=pw2[i-1]*p2%m2;}
struct node{ll h1,h2;inline ll getval(){return h1*m2+h2;}};
inline node ext(const node h,const int x){return {(h.h1*p1+rg1[x])%m1,(h.h2*p2+rg2[x])%m2};}
inline node apd(const node l,const node r,const int len){return {(l.h1*pw1[len]+r.h1)%m1,(l.h2*pw2[len]+r.h2)%m2};}
}
inline int frint(){int n=0;char c=getchar();while(c<'0'||'9'<c)c=getchar();while('0'<=c&&c<='9')n=n*10+c-48,c=getchar();return n;}
inline int frstr(char *s){int n=0;char c=getchar();while(c<'a'||'z'<c)c=getchar();while('a'<=c&&c<='z')s[++n]=c,c=getchar();return n;}
void wrll(ll x){if(x>9)wrll(x/10);putchar(x%10+48);}
struct DS1{
int idx,son[N][S],sz[N];
inline void ins(int n,char *s){int u=0;rep(i,1,n){int &v=son[u][s[i]-'a'];if(!v)v=++idx;sz[u=v]++;}}
ll res[N];umap<ll,int>pos;
inline void dfs(int u,HASH::node h){pos[h.getval()]=u;rep(i,0,S-1){int v=son[u][i];if(!v)continue;res[v]=res[u]+sz[v],dfs(v,HASH::ext(h,i));}}
}tr;
int n,m,q,k;char a[N];vector<HASH::node>hs[N];
inline ll ask(const arr a){
HASH::node h={0,0};rep(i,1,SZ(a)){
const int id=a[i-1],len=SZ(hs[id]);HASH::node h_=HASH::apd(h,hs[id][len-1],len);
if(!tr.pos.count(h_.getval())){
int res=0;for(int l=1,r=len-1,mid;mid=l+r>>1,l<=r;)
if(tr.pos.count(HASH::apd(h,hs[id][mid-1],mid).getval()))res=mid,l=mid+1;else r=mid-1;
if(res)h=HASH::apd(h,hs[id][res-1],res);
return tr.res[tr.pos[h.getval()]];
}h=h_;
}return tr.res[tr.pos[h.getval()]];
}
void main(){
HASH::Init();
n=frint();rep(i,1,n)tr.ins(k=frstr(a),a);tr.dfs(0,{0,0});
m=frint();rep(i,1,m){hs[i].rsz(k=frstr(a));HASH::node h={0,0};rep(j,1,k)hs[i][j-1]=h=HASH::ext(h,a[j]-'a');}
q=frint();rep(_,1,q){arr a;rep(__,1,frint())a.pb(frint());wrll(ask(a)),putchar('\n');}
}
}
int main(){
auto _Tbe=TIME;
c0dE1ng::main();
auto _Ted=TIME;
cerr<<"\nTIME:"<<_Ted-_Tbe<<'\n';
return 0;
}
/*
ulimit -v 1048576;ulimit -s 1048576
g++ -O2 -std=c++14 -static A.cpp -o A.exe;size A.exe;./A.exe < A.in > A.out
*/
:::