您的位置:首页 > 其它

POJ 1200 Crazy Search

2014-04-30 18:38 441 查看
思路:利用Karp-Rabin算法的思想,对每个子串进行Hash,如果Hash值相等则认为这两个子串是相同的(事实上还需要做进一步检查),Karp-Rabin算法的Hash函数有多种形式,但思想都是把字符串映射成一个数字。本题hash函数是把字串转化为NC进制的数(实际上程序中计算结果已经被转换为10进制,因为NC进制数不同转化为10进制数自然不同,所以不影响判断结果),数组开到了1.6×10^7(我试了一下1.2×10^7也能AC),实际上这也是不严谨的,因为我们不能保证hash之后的数值在这个范围内,比如N=NC=35,程序就有Bug了,但是这题后台数据可能没这么给。在实际运用中是需要取模的,而且即使hash值相等也需要进一步比对。

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
bool hash[16000005];
int is_have[300];
char str[1000005];
int main(){
int n, nc;
/* freopen("in.c", "r", stdin); */
while(~scanf("%d%d", &n, &nc)){
memset(str, 0, sizeof(str));
memset(hash, 0, sizeof(hash));
memset(is_have, 0, sizeof(is_have));
scanf("%s", str);
int len = strlen(str);
int k = 0, ans = 0;
for(int i = 0;i < len;i ++) is_have[str[i]] = 1;
for(int i = 0;i < 256;i ++)
if(is_have[i]) is_have[i] = k++;
for(int i = 0;i <= len - n;i ++){
int key = 0;
for(int j = i;j < i + n;j ++) key = key*nc + is_have[str[j]];
if(!hash[key]) ans ++, hash[key] = 1;
}
printf("%d\n", ans);
}
return 0;
}


下面附上一般情况的实现代码(均来自其他网友):

1. 原文链接:http://www.xefan.com/archives/83853.html


#include <stdio.h>
#include <math.h>
int mod = 0x7fffffff;
const int d = 128;
int rabin_karp(char *T, char *P, int n, int m)
{
if (n < m) return -2;
int h = pow(d, m-1);
int p = 0;
int t = 0;
int i, j;
for (i=0; i<m; i++) {
p = (d*p + P[i]) % mod;
t = (d*t + T[i]) % mod;
}
for (j=0; j<=n-m; j++) {
if (p == t) {
return j;
}
if (j < n-m) {
t = (d*(t - h*T[j]) + T[j+m]) % mod;
}
}
return -1;
}

int main(int argc, char *argv[])
{
char t[] = "BBC ABCDAB ABCDABCDABDE";
char p[] = "ABCDABD";
int len1 = sizeof(t) - 1;
int len2 = sizeof(p) - 1;
int index = rabin_karp(t, p, len1, len2);
printf("index: %d\n", index);
return 0;
}


2.原文链接:http://blog.csdn.net/onezeros/article/details/5531354

//Karp-Rabin algorithm,a simple edition
int karp_rabin_search(const char* text,const int text_len,const char* pattern,const int pattern_len)
{
int hash_text=0;
int hash_pattern=0;
int i;

//rehash constant:2^(pattern_len-1)
int hash_const=1;
/*for (i=1;i<pattern_len;i++){
hash_const<<=1;
}*/
hash_const<<=pattern_len-1;

//preprocessing
//hashing
for (i=0;i<pattern_len;++i){
hash_pattern=(hash_pattern<<1)+pattern[i];
hash_text=(hash_text<<1)+text[i];
}

//searching
for (i=0;i<=text_len-pattern_len;++i){
if (hash_pattern==hash_text&&memcmp(text+i,pattern,pattern_len)==0){
return i;
}else{
//rehash
hash_text=((hash_text-text[i]*hash_const)<<1)+text[i+pattern_len];
}
}
return -1;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: