POJ 1200 Crazy Search(简单哈希)

题目链接:http://poj.org/problem?id=1200


题意:给出不同字符个数不超过NC的一个字符串,问长度为n的不同子串有多少个?

思路:因为母串字符种类不超过NC,所以将母字符串转化成NC进制的一串数字串,因为母串的所有不同字串个数不超过16 million,所以枚举每个长度为N的子串的哈希值可过

注意:虽然子串的总数不超过16 million,但是hash值会大于16 million。

代码:

#include<iostream>
#include <cmath>
#include <cstdio>
#include <cstring>
using namespace std;
int const MAXN = 1600000+7;
int n,nc;//NC为text可能的最多有NC个字符不同,所以将字符串转化成NC进制,给text出现的字符赋予对应的数字,从0~NC,然后Hash
char T[MAXN];
bool hash[20000007];//hash表开到最大==,小了可能挂
int temp,count;
int num[MAXN];
int Hash()
{
    count = 0;
    int m = strlen(T);
    for(int i = 0;i<m-n+1;i++)
    {
        temp = 0;
        for(int j = i;j<i+n;j++)
        {
            temp = (temp*nc+(num[T[j]]))%20000007;
        }
         if(!hash[temp])
        {
                hash[temp] = 1;
                count++;
        }
    }
    return count;
}

int main()
{
    while(~scanf("%d%d",&n,&nc))
    {
        scanf("%s",T);
        memset(hash,0,sizeof(hash));
        memset(num,0,sizeof(num));
        int nums = 0;
        for(int i = 0;i<strlen(T);i++)
        {
            if(!num[T[i]])num[T[i]] = nums++;
        }
        cout<<Hash()<<endl;
    }
    return 0;
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值