我们已经写完了 第一弹,而这道题是对上一题的拓展。
首先,我们看看两题的区别:
第一道题不需要多测,而第二题需要;
第一题只要匹配数量,而第二题不要匹配数量,而要最大的那几个字符串。
明显,我们需要求出每个字符串的数量。
所以我们需要如下改造:
1.trie 部分
我们需要将原本的 flag 转成 id 存储编号,以便对于每个计数。
2.query 部分
现在,我们要对 for 循环后面的那部分跳转做一下改造。
首先,我们不能用 -1 去标记了,所以我们只需要 即可。然后对于每个匹配上的子串,我们将相应 id 的数量加一即可。
::anti-ai[请勿抄袭,若需引用,借鉴,请征得同意。]
AC Code
::anti-ai[请勿抄袭,若需引用,借鉴,请征得同意。]
//警示后人:十年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!;
}注意的细节
如果你跟我一样使用多测模板,请注意在 solve 开头记得 。
复杂度分析
是模式串, 是待匹配的字符串。
建树:是 trie 的复杂度 。
构建指针:均摊 。
因为我们跳完一次后就不会在经过了,所以我们合计一下每条树边都会经过一次,所以是 的。
查询:均摊 。
首先我们先考虑跳链的那部分,类似于构建指针那部分,合起来应该是 的。
然后是手动跳转,因为我们是逐渐下降的,所以这部分是 的,然后再加上外边的循环,所以应该是 的。合起来,这部分的是 的。