Singing Superstar 字符串哈希-map操作

在这里插入图片描述在这里插入图片描述

题意 :

  • 给一长度 < 1e5 的字符串s,q < 1e5次询问,每次问一个长 < 30 的串 t 在s中出现的次数,且t不可重叠。
  • 例 : “abababa“中“aba“不相交的出现的次数为2。

思路 :

  • 字符串题,对母串中所有长度小于等于30的串做字符串哈希,对相同哈希值的串暴力统计答案,每个询问直接查询对应哈希值的答案。
  • 也可以使用Trie/AC自动机来通过本题。
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <set>
#include <map>
#define endl '\n'
#define IOS ios::sync_with_stdio(false); cin.tie(0); cout.tie(0)
using namespace std;
const double pi = acos(-1);
typedef long long ll;

typedef unsigned long long ull;

const int N = 1e5 + 10, P = 131;

ull h[N], p[N];
ull a[N];		// 记录每个询问串的哈希值
char str[N];

ull get(int l, int r)
{
    return h[r] - h[l - 1] * p[r - l + 1];
}
         
int main()
{
    int T;
    scanf("%d", &T);
    
    while (T -- )
    {
        scanf("%s", str + 1);
        int len = strlen(str + 1);
        
        p[0] = 1;
        for (int i = 1; i <= len; i ++ )
        {
            p[i] = p[i - 1] * P;
            h[i] = h[i - 1] * P + str[i];
        }
        
        int n;
        scanf("%d", &n);
        
        map<ull, int> ma;		// 询问串哈希值在母串中出现的不相交的次数
        map<ull, int> last;		// 询问串哈希值在母串中上次出现的位置的末端
        
        for (int i = 1; i <= n; i ++ )
        {
            char buf[35];
            scanf("%s", buf + 1);
            int size = strlen(buf + 1);
            // 处理询问串哈希值
            ull x = 0;
            for (int j = 1; j <= size; j ++ )
                x = x * P + buf[j];
            
            a[i] = x;
            ma[a[i]] = 0;
            last[a[i]] = 0;
        }
        
        // 暴力枚举母串中长度小于等于30的串的哈希值
        for (int i = 1; i <= len; i ++ )
        {
            for (int j = 0; j < 30 && i + j <= len; j ++ )
            {
                ull x = get(i, i + j);
                // []包含了插入,count不插入,count查询是logn
                if (ma.count(x) && last[x] < i)
                {
                    ma[x] ++ ;
                    last[x] = i + j;
                }
            }
        }
        
        for (int i = 1; i <= n; i ++ )
            printf("%d\n", ma[a[i]]);
    }
                 
    return 0;
}

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值