変わったAho-Corasickの方法。
http://codeforces.com/contest/1437/problem/G
問題
以下のクエリに答えよ。
- 文字列Sに対し、M[S]=xと値を設定する。
- 文字列Qが与えられる。Qの連続部分文字列qのうち、M[q]の最大値を求めよ。
解法
まずSに対しAho-Corasick法を使う準備をしておく。
Qに対し、Aho-Corasick法を適用するわけだが、部分文字列の条件より、実際はQの先頭何文字かが存在しない場合の遷移を考えなければならない。
ただ、これはAho-Corasickにおいてsuffix linkをたどることに相当する。
そこで、Aho-Corasickにおいて1文字遷移するたびに、Suffix linkをたどれるだけたどることを行う。
とはいえ、同じノードを何回も通っても無駄なので、後者のクエリ1回に対し、各ノードは重複してSuffix linkをたどらないようにしよう。
const int NUMC=26; class Trie { public: vector<vector<int> > V; int find(string s) { int cur=0; ITR(it,s) if((cur=V[cur][*it+1])==0) return -1; return cur; } void create(vector<string> S) { // 0 is for backtrack V.clear(); V.push_back(vector<int>(NUMC+1)); sort(S.begin(),S.end()); ITR(it,S) { int cur=0; ITR(c,(*it)) { if(V[cur][*c+1]==0) V.push_back(vector<int>(NUMC+1)),V[cur][*c+1]=V.size()-1; cur=V[cur][*c+1]; } } } }; int tid; class ACmatch_enum { public: Trie t; vector<multiset<int> > acc; vector<int> po; vector<int> ev; int ma; void create(vector<string> S) { int i; ma=S.size(); t.create(S); acc.clear(); acc.resize(t.V.size()); ev.resize(t.V.size()); po.resize(ma); FOR(i,S.size()) { po[i]=t.find(S[i]); acc[po[i]].insert(0); } queue<int> Q; FOR(i,NUMC) if(t.V[0][i+1]) t.V[t.V[0][i+1]][0]=0, Q.push(t.V[0][i+1]); while(!Q.empty()) { int k=Q.front(); Q.pop(); FOR(i,NUMC) if(t.V[k][i+1]) { Q.push(t.V[k][i+1]); int pre=t.V[k][0]; while(pre && t.V[pre][i+1]==0) pre=t.V[pre][0]; t.V[t.V[k][i+1]][0]=t.V[pre][i+1]; } } } int match(string S) { int ret=-1; tid++; int cur=0; FORR(c,S) { c-='a'; while(cur && t.V[cur][c+1]==0) cur=t.V[cur][0]; cur=t.V[cur][c+1]; int tmp=cur; while(tmp&&ev[tmp]<tid) { ev[tmp]=tid; if(acc[tmp].size()) ret=max(ret,*acc[tmp].rbegin()); tmp=t.V[tmp][0]; } } return ret; } }; int N,M; vector<string> S; string T; int V[303030]; ACmatch_enum ac; void solve() { int i,j,k,l,r,x,y; string s; cin>>N>>M; FOR(i,N) { cin>>s; FORR(c,s) c-='a'; S.push_back(s); } ac.create(S); FOR(i,M) { cin>>j; if(j==1) { cin>>x>>y; x--; ac.acc[ac.po[x]].erase(ac.acc[ac.po[x]].find(V[x])); V[x]=y; ac.acc[ac.po[x]].insert(y); } else { cin>>T; cout<<ac.match(T)<<endl; } } }
まとめ
なるほど…。