hdu1381 hash

来源:互联网 发布:流程图软件推荐 编辑:程序博客网 时间:2024/06/04 18:59

http://www.cnblogs.com/gj-Acit/archive/2013/05/15/3080734.html


题目大意就是将一个字符串分成长度为N的字串。且不同的字符不会超过NC个。问总共有多少个不同的子串。最初看了半天一直没看明白与哈希有什么关系(相信也有人和这个菜鸟我一样吧),无奈之下只好去搜结题报告,突然才明白原来那个NC作用大大。

最后采用的办法就是以nc作为进制,把一个子串化为这个进制下的数,再用哈希判断。由于题目说长度不会超过16,000,000  所以哈希长度就设为16000000就行。另外为每一个字符对应一个整数,来方便转化。

如题目中的

daababac与整数对应之后就是

12232324

然后子串

daa->122->011(因为是化为4进制,所以需要减1)->5(因为是4进制);

aab->223->112->22;

aba->232->121->25;


#include<stdio.h>
#include<string.h>
#define mem(a) memset(a,0,sizeof(a))


unsigned int hash[16000000+5];
unsigned int c[128];
char str[1000000];


int main()
{
    int len,base;
    while(~scanf("%d%d",&len,&base))
    {
        mem(str);
        mem(c);
        mem(hash);
        scanf("%s",str);
        int num =0;
        int i,j=0,length=strlen(str),tp=1;
        for(i=0;i<length;i++)
        {
            if(c[str[i]]==0)c[str[i]]=++j;
            if(j==base)break;
        }
        for(i=0;i<len;i++)
        {
            num=num*base+c[str[i]]-1;
            tp*=base;
        }
        tp/=base;
        hash[num]=1;
        int count=1;
        for(i=1;i<=length-len;i++)
        {
            num = ( num-(c[str[i-1]]-1)*tp )* base+ c[str[i+len-1]] - 1;
            if(!hash[num])
            {
                hash[num]=1;
                count++;
            }
        }
        printf("%d\n",count);
    }
    return 0;
}

0 0
原创粉丝点击