poj1200 Crazy Search(hash)

题目大意就是将一个字符串分成长度为N的字串。且不同的字符不会超过NC个。问总共有多少个不同的子串。

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

#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>

using namespace std;

const int maxn=1600000;

int n,nc;
bool c[20000000];
char s[maxn];
int Hash[256];


int main()
{
    ios::sync_with_stdio(false);cin.tie(0);
    while(cin>>n>>nc)
    {
        cin>>s;
        memset(c,false,sizeof(c));
        memset(Hash,0,sizeof(Hash));
        int len=strlen(s);
        int tmp;

        int cnt=0;
        for(int i=0;i<len;i++){
            if(Hash[s[i]]==0)
            {
                Hash[s[i]]=cnt++;
            }
        }
        int ans=0;
        for(int i=0;i+n<=len;i++)
        {
            tmp=0;
            for(int j=i;j<i+n;j++)
            {
                tmp*=nc;
                tmp+=Hash[s[j]];
            }
            if(!c[tmp])
            {
                ans++;
                c[tmp]=true;
            }
        }

        cout<<ans<<endl;


    }
    return 0;
}
原文地址:https://www.cnblogs.com/Fy1999/p/9444303.html