计算出文本串每连续八个字符的hash值,并统计文本串中各hash值出现的次数,这样在输入模式串的之后计算出模式串的hash值直接累加即可。(本题要求串和串之间的匹配标准可以无序,例如:ababc和cbaba可以匹配,因为两个串包含的字符完全一样,经过一定的排序后两串可以相同。)这样我们计算hash值的时候统一按照相同的标准计算(这里本人使用每连续8个字符从小到大排序);
#include <iostream>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <vector>
#include <map>
#include <queue>
#include <cstdio>
#include <string>
#include <stack>
#include <set>
#define IOS ios::sync_with_stdio(false), cin.tie(0)
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const ll seed=131;
ull hs;
map<ull,ll> cnt;
string s;
void gethash(int id){//计算s[id,id+7]的hash值
hs=0;
string temp;
temp=s.substr(id,8);
sort(temp.begin(),temp.end());//统一计算标准
for(int i=0;i<8;i++){//计算hash值
hs=hs*seed+temp[i];
}
}
void hash_cnt(ll len,bool select){//select判断输入的是文本串还是模式串
gethash(0);
if(select)return ;//如果是模式串只需要计算hash值
cnt[hs]++;
for(int i=8;i<len;i++){
gethash(i-7);
cnt[hs]++;
}
return ;
}
int main()
{
IOS;
ll n;
bool en=false;//en表示s不足8个字符
cin>>s;
ll len=s.length();
if(len<8)en=true;
if(!en)
hash_cnt(len,false);
cin>>n;
ll ans=0;
while(n--){
cin>>s;
if(en)continue;
hash_cnt(8,true);
ans+=cnt[hs];//累计hs在文本串中出现的次数,即为匹配的次数
}
cout<<ans<<endl;
getchar();
getchar();
return 0;
}