HDU-4821 String

原题链接:

https://vjudge.net/problem/HDU-4821

AC代码:

#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int INF = 0x3fffffff;
typedef long long ll;
typedef unsigned long long ull;

void __init__()
{
    ios::sync_with_stdio(false);
    cin.tie(0), cout.tie(0);
}//head

const ll maxn = 1e5 + 10;
const int p = 1331;
char s[maxn];
ull base[maxn];
ull hasH[maxn];

void get_base()
{
    base[0] = 1;
    for (int i = 1; i < maxn; i++)
    {
        base[i] = base[i - 1] * p;
    }
}

void get_hash(int len, char s[])
{
    for (int i = 1; i <= len; i++)
    {
        hasH[i] = hasH[i - 1] * p + s[i] - 'a';
    }
}

ull get_subhash(int l, int r)
{
    return hasH[r] - hasH[l - 1] * base[r - l + 1];
}

int main()
{
    // __init__();
    get_base();
    int l, m;
    while (scanf("%d%d", &m, &l) != EOF)
    {
        cin >> s + 1;
        int len = strlen(s + 1);
        get_hash(len, s);

        int ans = 0;
        for (int i = 1; i <= l && i + l * m <= len; i++)
        {
            map<ull, int> hsmp;
            for (int j = i; j <= i + l * m - 1; j += l)
            {
                ull x = get_subhash(j, j + l - 1);
                hsmp[x]++;
            }
            if (hsmp.size() == m)
            {
                ans++;
            }
            for (int j = i + l * m; j + l - 1 <= len; j += l)
            {
                ull x = get_subhash(j, j + l - 1);
                hsmp[x]++;
                x = get_subhash(j - l * m, j - l * m + l - 1);
                hsmp[x]--;
                if (hsmp[x] == 0)
                    hsmp.erase(x);
                if (hsmp.size() == m)
                {
                    ans++;
                }
            }
        }
        printf("%d\n", ans);
    }

    return 0;
}

日常补题,跟大佬学到了字符串哈希的用法,为了优化时间复杂度,遍历采用了尺取法进行遍历。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值