总结
KMP算法
前缀函数
map<xxx,vector<xxx> >
优先队列,dp练习
题解整合
SMU Summer 2024 Contest Round 6 ABC题解-CSDN博客
河南萌新联赛2024第(二)场 AEFHIJ题解-CSDN博客
SMU Summer 2024 Contest Round 7 ABCDG-CSDN博客
KMP算法与前缀函数
前缀函数与KMP算法相互配合,是相对find();更优的字符串匹配算法,其核心为使用两个指针使每次匹配能够跳过一些部分,从而能够减少时间复杂度
例题:
E “好”字符
思路:将第二个字符串后再加一个第二字符串,方便 循环同构的操作,枚举出现过的字母,每次枚举中将两个字符串中非当前枚举字符的字符变为 ‘*’ ,然后判断第一字符串是否为第二字符串的子串即可 注意:这里用find()会TLE,所以要使用前缀函数+kmp算法来解决
AC代码:
#include<bits/stdc++.h>
using namespace std;
int n;
string s1,s2;
vector<int> prefix_function(const string &s){
int n = s.size();
vector<int> pi(n);
for(int i = 1, j; i < n; i ++) {
j = pi[i - 1];
while(j > 0 and s[i] != s[j]) j = pi[j - 1];
if(s[i] == s[j]) j ++;
pi[i] = j;
}
return pi;
}
bool kmp(const string &text, const string &pattern) {
string cur = pattern + "#" + text;
int n = text.size(), m = pattern.size();
vector<int> lps = prefix_function(cur);
for(int i = m + 1; i <= n + m; i ++) {
if(lps[i] == m) return true;
}
return false;
}
int main(){
cin>>n;
cin>>s1;
cin>>s2;
s2 += s2;
vector<int> cnt1('z'+1),cnt2('z'+1);
for(auto i:s1) cnt1[i]=1;
for(auto i:s2) cnt2[i]=1;
int ans = 0;
for(char c='a';c<='z';c++){
if(cnt1[c]==0 || cnt2[c]==0) continue;
string aa = s1 , bb = s2;
for(auto& i:aa) if(i!=c) i='*';
for(auto& i:bb) if(i!=c) i='*';
if(kmp(bb,aa)) ans++;
}
cout<<ans<<endl;
return 0;
}
map<xxx,vector<xxx> >
在cf近期一场 div2 的B中最初使用,因为数据给到了10^18,使用开数组不行,这个时候用map<xxx,vector<xxx> >来进行记录和维护就非常方便,之后在河南萌新多校赛中也用上了
例题:
狼狼的备忘录
思路: 用map<string,vector<string> >来维护,map自带排序,vector可以方便的排序与删改
AC代码:
#include<bits/stdc++.h>
using namespace std;
bool endsWith(string str,string suffix) {
if (suffix.length() > str.length()) { return false; }
return (str.rfind(suffix) == (str.length() - suffix.length()));
}
map<string, vector<string> >peo;
int main(){
ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
int n;
cin>>n;
for(int i=1;i<=n;i++){
string namm;
int x;
string aa;
cin>>namm>>x;
for(int j=0;j<x;j++){
cin>>aa;
peo[namm].push_back(aa);
}
}
for(auto& xx:peo){
sort(xx.second.begin(),xx.second.end());
// for(int j=0;j<xx.second.size();j++) cout<<xx.second[j]<<" ";
// cout<<endl;
for(int j=0;j<xx.second.size();j++){
for(int k=0;k<xx.second.size();k++){
if(k!=j && endsWith(xx.second[k],xx.second[j]) ){
xx.second.erase(xx.second.begin()+j); j--;//注意这里删了一个,j要退一格
break;
}
}
}
}
cout<<peo.size()<<endl;
for(auto& xx:peo){
cout<<xx.first<<" "<<xx.second.size()<<" ";
for(int j=0;j<xx.second.size();j++) cout<<xx.second[j]<<" ";
cout<<endl;
}
return 0;
}