P2414-[NOI2011]阿狸的打字机【AC自动机,树状数组】
生活随笔
收集整理的這篇文章主要介紹了
P2414-[NOI2011]阿狸的打字机【AC自动机,树状数组】
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
正題
題目鏈接:https://www.luogu.com.cn/problem/P2414
題目大意
一個子串表示操作有
然后每次詢問兩個數(shù)字(x,y)(x,y)(x,y)表示詢問第xxx行的字串在第yyy行的字串里出現(xiàn)了多少次
解題思路
考慮ACACAC自動機(jī)上如何求子串關(guān)系,首先我們可以一個位置的failfailfail指向的位置表示指向代表的串是該位置的串的后綴。所以我們可以發(fā)現(xiàn)一個詢問(x,y)(x,y)(x,y)其實(shí)就是詢問yyy這個串在TrieTrieTrie上的所有點(diǎn)有多少的failfailfail指針可以指向xxx的結(jié)束位置。
然后可以在failfailfail的指向反過來之后就成了一棵樹,然后對于每個點(diǎn)會影響一段連續(xù)的區(qū)間,我們可以用樹狀數(shù)組維護(hù)即可
codecodecode
#include<cstdio> #include<cstring> #include<algorithm> #include<queue> #include<vector> #define lowbit(x) (x&-x) using namespace std; const int N=2e5+10; struct node{int to,next; }a[N*2]; int n,m,num,tot,cnt,pos[N],ls[N],ans[N]; int t[N],fa[N],fail[N],dfn[N],ed[N],w[N]; int son[N][26],ch[N][26]; char s[N]; queue<int> q; vector<int> que[N]; void init(){scanf("%s",s);int len=strlen(s),x=0;for(int i=0;i<len;i++){if(s[i]=='B')x=fa[x];else if(s[i]=='P'){pos[++m]=x;}else{int c=s[i]-'a';if(!son[x][c]){son[x][c]=++num;fa[num]=x;}x=son[x][c];}}return; } void Change(int x,int val){while(x<=cnt){t[x]+=val;x+=lowbit(x);}return; } int Ask(int x){int ans=0;while(x){ans+=t[x];x-=lowbit(x);}return ans; } void addl(int x,int y){a[++tot].to=y;a[tot].next=ls[x];ls[x]=tot;return; } void get_fail(){memcpy(ch,son,sizeof(ch));for(int i=0;i<26;i++)if(ch[0][i])q.push(ch[0][i]);while(!q.empty()){int x=q.front();q.pop();for(int i=0;i<26;i++)if(!ch[x][i])ch[x][i]=ch[fail[x]][i];else{q.push(ch[x][i]);int y=fail[x];fail[ch[x][i]]=ch[y][i];}}for(int i=1;i<=num;i++)addl(i,fail[i]),addl(fail[i],i);return; } void dfs_fail(int x,int fa){dfn[x]=++cnt;for(int i=ls[x];i;i=a[i].next){int y=a[i].to;if(y==fa)continue;dfs_fail(y,x);}ed[x]=cnt;return; } void dfs_trie(int x){Change(dfn[x],1);for(int i=0;i<que[x].size();i++){int pos=que[x][i];ans[pos]=Ask(ed[w[pos]])-Ask(dfn[w[pos]]-1);}for(int i=0;i<26;i++)if(son[x][i])dfs_trie(son[x][i]);Change(dfn[x],-1);return; } int main() { init();get_fail();scanf("%d",&n);for(int i=1;i<=n;i++){int y;scanf("%d%d",&w[i],&y);que[pos[y]].push_back(i);w[i]=pos[w[i]];} dfs_fail(0,0);dfs_trie(0);for(int i=1;i<=n;i++)printf("%d\n",ans[i]); }總結(jié)
以上是生活随笔為你收集整理的P2414-[NOI2011]阿狸的打字机【AC自动机,树状数组】的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 何洁个人资料简介 何洁是哪里人
- 下一篇: P3041-[USACO12JAN]Vi