AC自动机de指针版题解第二弹
Simon439747 · · 题解
我们已经写完了 第一弹,而这道题是对上一题的拓展。
首先,我们看看两题的区别:
第一道题不需要多测,而第二题需要;
第一题只要匹配数量,而第二题不要匹配数量,而要最大的那几个字符串。
明显,我们需要求出每个字符串的数量。
所以我们需要如下改造:
1.trie 部分
我们需要将原本的 flag 转成 id 存储编号,以便对于每个计数。
2.query 部分
现在,我们要对 for 循环后面的那部分跳转做一下改造。
首先,我们不能用 -1 去标记了,所以我们只需要
//警示后人:十年OI一场空,不开long long见祖宗
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define AC 0
using ll=long long;
using pll=pair<int,int>;
template<typename T>
inline void readinVector(vector<T>& vec,int l,int r){
for(int i=l;i<=r;i++)cin>>vec[i];
}
template<typename T>
class matvec{
public:
vector<vector<T> >mat;
matvec(){}
matvec(int n){
mat.resize(n+1);
}
void rs(int n){
mat.resize(n+1);
}
matvec(int n,int m){
mat.resize(n+1,vector<T>(m+1));
}
matvec(int n,int m,T v){
mat.resize(n+1,vector<T>(m+1,v));
}
vector<T>& operator[](int i){
return mat[i];
}
void p_b(const vector<T>&vec){
mat.push_back(vec);
}
};
struct trie{
unordered_map<char,trie*>nxt;
int id;
trie* fail;
trie():id(-1),fail(nullptr){}
void add(const string& s,int idx,int pos=0){
if(pos==s.length()){
id=idx;
return ;
}
if(!nxt.count(s[pos]))nxt[s[pos]]=new trie();
nxt[s[pos]]->add(s,idx,pos+1);
}
};
trie* dieHead=new trie();
void getFail(trie* root){
queue<trie*>q;
root->fail=dieHead;
for(auto [c,v]:root->nxt){
v->fail=root;
q.push(v);
}
while(!q.empty()){
trie* u=q.front();
q.pop();
for(auto [c,v]:u->nxt){
trie* f=u->fail;
while(f!=dieHead&&!f->nxt.count(c))f=f->fail;
if(f->nxt.count(c)){
v->fail=f->nxt[c];
}else v->fail=root;
q.push(v);
}
}
}
vector<int>tot;
void query(const string& s,trie* root){
trie* u=root;
for(char c:s){
while(u!=dieHead&&!u->nxt.count(c))u=u->fail;
if(u->nxt.count(c))u=u->nxt[c];
else u=root;
trie* j=u;
while(j!=dieHead){
if(j->id!=-1){
tot[j->id]++;
}
j=j->fail;
}
}
}
int T=1;
void solve(){
tot.clear();
trie* root=new trie();
int n=T;
tot.resize(n+1);
vector<string>strs(n+1);
for(int i=1;i<=n;i++){
cin>>strs[i];
root->add(strs[i],i);
}
getFail(root);
string s;
cin>>s;
query(s,root);
int maxn=*max_element(tot.begin()+1,tot.end());
cout<<maxn<<endl;
for(int i=1;i<=n;i++){
if(tot[i]==maxn){
cout<<strs[i]<<endl;
}
}
}
signed main(){
// freopen("xxx.in","r",stdin);
// freopen("xxx.out","w",stdout);
ios::sync_with_stdio(false);
cin.tie(nullptr);
while(cin>>T){
if(T==0)break;
solve();
}
return AC;
//AK IOI!;
}
::::
::::warning[注意的细节]
如果你跟我一样使用多测模板,请注意在 solve 开头记得
:::info[复杂度分析]