POJ-1200 Crazy Search(hash)

Crazy Search
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 27336   Accepted: 7641

Description

Many people like to solve hard puzzles some of which may lead them to madness. One such puzzle could be finding a hidden prime number in a given text. Such number could be the number of different substrings of a given size that exist in the text. As you soon will discover, you really need the help of a computer and a good algorithm to solve such a puzzle. 
Your task is to write a program that given the size, N, of the substring, the number of different characters that may occur in the text, NC, and the text itself, determines the number of different substrings of size N that appear in the text. 

As an example, consider N=3, NC=4 and the text "daababac". The different substrings of size 3 that can be found in this text are: "daa"; "aab"; "aba"; "bab"; "bac". Therefore, the answer should be 5. 

Input

The first line of input consists of two numbers, N and NC, separated by exactly one space. This is followed by the text where the search takes place. You may assume that the maximum number of substrings formed by the possible set of characters does not exceed 16 Millions.

Output

The program should output just an integer corresponding to the number of different substrings of size N found in the given text.

Sample Input

3 4
daababac

Sample Output

5

Hint

Huge input,scanf is recommended.

Source

好吧好吧,我这次就直接上别人的程序了(*^__^*) 

 1 #include<stdio.h>
 2 #include<string.h>
 3 #define mem(a) memset(a,0,sizeof(a))
 4 
 5 unsigned int hash[16000000+5];
 6 unsigned int c[128];
 7 char str[1000000];
 8 
 9  int main()
10  {
11      int len,base;
12      while(~scanf("%d%d",&len,&base))
13      {
14          mem(str);
15          mem(c);
16          mem(hash);
17          scanf("%s",str);
18         int num =0;
19          int i,j=0,length=strlen(str),tp=1;
20          for(i=0;i<length;i++)
21         {
22              if(c[str[i]]==0)c[str[i]]=++j;
23              if(j==base)break;
24          }
25          for(i=0;i<len;i++)
26          {
27              num=num*base+c[str[i]]-1;
28              tp*=base;
29          }
30          tp/=base;
31          hash[num]=1;
32          int count=1;
33          for(i=1;i<=length-len;i++)
34          {
35             num = ( num-(c[str[i-1]]-1)*tp )* base+ c[str[i+len-1]] - 1;
36              if(!hash[num])
37              {
38                  hash[num]=1;
39                  count++;
40              }
41          }
42          printf("%d\n",count);
43      }
44      return 0;
45  }

 

posted @ 2016-08-12 22:19  lonely_OIer  阅读(174)  评论(0编辑  收藏  举报