Poj 1200 --- a good string hash Construction Method

Source: Internet
Author: User

Question: http://poj.org/problem? Id = 1200

For a string, given n and NC, the string contains a maximum of NC characters. The maximum number of different substrings with N length can be:

Like the one in the last field competition, it is also difficult to judge and rehandle the problem and it will time out.

Method: map a substring with a length of N to an NC number, and open a large array to check whether the substring is repeated.

#include <cstdio>#include <cstring>#include <algorithm>#include <string>#include <iostream>#include <cmath>#include <map>#include <map>#include <queue>using namespace std;#define ls(rt) rt*2#define rs(rt) rt*2+1#define ll long long#define ull unsigned long long#define rep(i,s,e) for(int i=s;i<e;i++)#define repe(i,s,e) for(int i=s;i<=e;i++)#define CL(a,b) memset(a,b,sizeof(a))#define IN(s) freopen(s,"r",stdin)#define OUT(s) freopen(s,"w",stdin)const int MAXN = 16000000+100;bool Hash[MAXN];char str[MAXN];int m[1001];int n,nc;int ah,base;///int main(){    //IN("poj1200.txt");    int ans,len,seed;    while(~scanf("%d%d",&n,&nc))    {        CL(Hash,0);CL(m,0);        ah=0;ans=0;seed=0;        scanf("%s",str);        len=strlen(str);        if(len<n){puts("0");continue;}        rep(i,0,len)        {            if(!m[str[i]])m[str[i]]=++seed;            if(seed == nc)break;        }        ah=m[str[0]],base=nc;        for(int i=1;i<n;i++)        {            ah=ah*nc+m[str[i]];            base*=nc;        }        Hash[ah]=1;ans++;        rep(i,n,len)        {            ah=ah*nc-m[str[i-n]]*base+m[str[i]];            if(!Hash[ah])            {                Hash[ah]=1;                ans++;            }        }        printf("%d\n",ans);    }    return 0;}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.