hdu-4821-String-HASH

http://acm.hdu.edu.cn/showproblem.php?pid=4821


题意:

给一个字符串S,和2个数L,M。    s'len<=1e5

问你有多少个的子串满足 如下条件:   

1、串长为M*L

2、能由M个 【长度为L】的  【不完全相同】的  【S的子串】 构成      (*)


(一个子串A与子串B的起始位置不同,即认为他们分别是2个子串,即答案数+2,与(*)中的【不完全相同】不一样)



暴力思路很简单,就是先预处理S,把每个长度为L的子串都hash成ull,然后遍历其每一个长度为M*L的子串看是否符合条件2即可。若符合,则答案数加1。


稍稍改进下就是,不用暴力匹配每一个长度为M*L的子串,只需要每次滑动L长度,维护一个M*L的串即可。


这里的基本单位是【每个长度为L的子串 hash成的一个ull数】

因此检测一个M*L串时,需要从某个地方开始,然后把在i,i+l,i+l+l,i+l+l+l....里滑动维护M*L的串

由于串长为L,最多需要从L个地方开始滑.....复杂度不会超过O(len)

Run IDSubmit TimeJudge StatusPro.IDExe.TimeExe.MemoryCode Len.LanguageAuthor
174772332016-07-09 18:25:45Accepted4821670MS3348K1675 BC++liuyuhong


#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
#include <vector>
#include <iostream>
using namespace std;
typedef  unsigned long long ull;
const double pi=acos(-1.0);
double eps=0.000001;

int M,L;
char s[100005];
int base=27;
ull tab[100005];
map<ull ,int > mp;

int main()
{


    while(cin>>M>>L)
    {

        int i,j;
        ull powsL_1=1;
        for (int i=1; i<=L-1; i++)
            powsL_1*=base;

        scanf("%s",s);
        int len=strlen(s);
        int st=0;
        ull tmp=0;
        for (j=0; j<L; j++)
        {
            tmp=tmp*base+s[j]-'a'+1;
        }
        tab[++st]=tmp;
        for (i=L; i<len; i++)       //滑动预处理所有长度为L的子串的hash值
        {
            tmp=tmp-(s[i-L]-'a'+1)*powsL_1;
            tmp=tmp*base+s[i]-'a'+1;
            tab[++st]=tmp;
        }

        int ans=0;
        int k;
        for (k=1; k<=L; k++)    //从k位置开始滑动
        {
            mp.clear();
            int num=0;
            int first=k;
            for (i=k; i<=st; i+=L)  //每次滑动到下一个l的距离
            {
                if (mp[tab[i]]==1)
                {
                    mp[tab[first]]--;
                    first+=L;
                    i-=L;
                    num--;
                    continue;
                }
                mp[tab[i]]=1;
                num++;
                if (num==M)     //找到符合条件的子串
                {
                    ans++;
                    mp[tab[first]]--;
                    first+=L;
                    num--;
                }

            }
        }

        printf("%d\n",ans);

    }
    return 0;
}




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值