計算出文本串每連續八個字符的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;
}