蓝桥杯训练——[蓝桥杯][2015年第六届真题]密文搜索(字符串hash解法)

题目链接:https://www.dotcpp.com/oj/problem1828.html

 

计算出文本串每连续八个字符的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;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值