您的位置:首页 > 其它

POJ 1200 Crazy Search hash入门

2016-06-12 15:11 375 查看
Crazy Search

Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 26383 Accepted: 7371
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


题意:给一个字符串,字符串中将出现nc种字符,计算长度为n的不同子串有多少个。

这道题的算法姿势和BKDRhash算法是非常类似的,都是使此字符前的字符串hash值乘一个常数再加上当前字符对应的数值。BKDRhash的常数是seed = 131,每个字符对应其ascii值,采用公式hash = hash*seed+s[i];计算需要的字符串hash值。
这道题类似的是对字符串中出现的每个字符赋一个初值,然后常数为那个nc
进行hach,对出现的每个hash值进行标记计数就行了。

我不是根据题意推这道题的做法,是根据这道题来理解我学习的hash算法。我的题解不具备解题思路的参考性。

CODE
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <string.h>

using namespace std;

const int N = 1600000+10;

char s
;
bool flag[N*20];

int main()
{
int n,nc;
while(scanf("%d%d%s",&n,&nc,s) != EOF)
{
memset(flag,false,sizeof flag);
int Hash[260] = {0};
int len = strlen(s);
int ans = 0;
int cnt = 0;
for(int i = 0;i < len;i++)
if(!Hash[s[i]])            ///将出现的每个字符对应一个值用于hash计算
Hash[s[i]] = cnt++;
for(int i = 0;i+n <= len;i++)
{
int sum = 0;
for(int j = i;j < i+n;j++) ///计算每个字串的hash值
{
sum *= nc;
sum += Hash[s[j]];
}
if(!flag[sum])
{
ans++;
flag[sum] = true;
}
}
printf("%d\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  hash