zoj1507 Crazy Search (hash )

给定字符串

n代表子串长度,nc代表字符串中元素的种类

在poj1200 hdu1381交过后交zoj

此题pe无限次。。。

#include <iostream>
#include <stdio.h>
#include <cstring>
#include <string>
using namespace std;
const int N=16000005; 

const int NUM=300;
bool hash[N];
int m[NUM];
char str[1000000];
int main()
{
    int tt;
    cin>>tt;
    while(tt--)
    {
        int n,nc,i,j,sum,seed=0,ans=0;
        memset(hash,false,sizeof(hash));
        memset(m,0,sizeof(m));
        memset(str,'\0',sizeof(str));
        cin>>n>>nc>>str;
        for(i=0; '\0' != str[i]; ++i)
        {
            if(!m[str[i]]) //将每个字符赋值为相应进制的数
                m[str[i]]=++seed;
            if(seed == nc)
                break;
        }
        int len=strlen(str);
        for(i=0; i<=len-n; ++i)
        {
            sum=0;
            for(j=0; j<n; ++j) 
          //将字符串str[i],..,str[i+n-1]变为一个nc进制的整数,来判断是否重复出现过
                sum=sum*nc+m[str[i+j]]-1;
            if(!hash[sum])
            {
                hash[sum]=true;
                ++ans;
            }
        }
       if(tt)
        cout<<ans<<endl<<endl;
        else
        cout<<ans;
    }
    return 0;
}


你可能感兴趣的:(search)