1. 程式人生 > >51nod1440 邁克打電話

51nod1440 邁克打電話

題目
和阿狸的打字機很像,差不多的套路

#include<bits/stdc++.h>
using namespace std;
#define mid ((l+r)>>1)
const int N=200002,M=4000002;
struct node{
	int to,ne;
}e[N];
int l1[N],r1[N],l[N],r[N],tr[N][26],sum,x,y,i,q[N],P,L[M],R[M],tot,cnt,tim,h[N],pos[N],fail[N],sm[M],le,ri,n,Q,rt[N],k;
char s[N];
#define gc getchar
inline int rd(){ int x=0,fl=1;char ch=gc(); for (;ch<48||ch>57;ch=gc())if(ch=='-')fl=-1; for (;48<=ch&&ch<=57;ch=gc())x=(x<<3)+(x<<1)+(ch^48); return x*fl; } inline void wri(int a){if(a>=10)wri(a/10);putchar(a%10|48);} inline void wln(int a){if(a<0)a=-a,putchar('-'
);wri(a),puts("");} void add(int x,int y){ e[++tot]=(node){y,h[x]}; h[x]=tot; } void dfs(int u){ l1[u]=++tim; for (int i=h[u];i;i=e[i].ne) dfs(e[i].to); r1[u]=tim; } void ins(char *s){ int k=0; for (int i=0;s[i];i++){ int &son=tr[k][s[i]-'a']; if (!son) son=++sum; k=son; pos[++cnt]=
k; } } void build(){ int h=0,t=1; while (h<t){ int u=q[h++]; for (int i=0;i<26;i++){ int &v=tr[u][i]; if (v){ if (u) fail[v]=tr[fail[u]][i]; q[t++]=v; }else v=tr[fail[u]][i]; } } } void update(int &rt,int pre,int l,int r){ rt=++tot,sm[rt]=sm[pre]+1; if (l==r) return; if (P<=mid) R[rt]=R[pre],update(L[rt],L[pre],l,mid); else L[rt]=L[pre],update(R[rt],R[pre],mid+1,r); } int query(int l,int r,int x,int y){ if (le<=l && r<=ri) return sm[x]-sm[y]; int ans=0; if (le<=mid) ans+=query(l,mid,L[x],L[y]); if (mid<ri) ans+=query(mid+1,r,R[x],R[y]); return ans; } int main(){ n=rd(),Q=rd(); for (i=1;i<=n;i++) scanf("%s",s),l[i]=cnt+1,ins(s),r[i]=cnt; build(); for (i=1;i<=sum;i++) add(fail[i],i); tot=0,dfs(0),sum++; for (i=1;i<=cnt;i++) P=l1[pos[i]],update(rt[i],rt[i-1],1,sum); for (;Q--;){ x=rd(),y=rd(),k=rd(); le=l1[pos[r[k]]],ri=r1[pos[r[k]]]; wln(query(1,sum,rt[r[y]],rt[l[x]-1])); } }