poj1200-CrazySearch(Rabin-Karp Hash)

来源:互联网 发布:java 单例模型 编辑:程序博客网 时间:2024/05/19 13:42
#include <cstdio>#include <cstring>#include <algorithm>using namespace std;#define MAXC    1<<9#define MAXCH   1<<20#define MAXN    16000005char str[MAXCH];int  val[MAXC];bool hash[MAXN];int main(int argc, char const *argv[]){#ifndef ONLINE_JUDGE        freopen("test.in", "r", stdin);#endif        int idx, sub_len, diff, rst, len;        while( ~scanf("%d %d", &sub_len, &diff) ) {                scanf("%s", str); rst = 0;                memset(val, -1, sizeof(val)); memset(hash, false, sizeof(hash));                for(int i = 0, cnt = 0; cnt <= diff && '\0' != str[i]; i ++) {                        if( -1 != val[str[i]] ) {                                continue;                        }                        val[str[i]] = cnt ++;                }                len = strlen(str);                for(int i = 0; i <= len-sub_len; i ++) { idx = 0;                        for(int j = i; j < i+sub_len; j ++) {                                idx = idx*diff+val[str[j]];                        }                        if( true == hash[idx] ) {                                continue;                        }                        hash[idx] = true; rst += 1;                }                printf("%d\n", rst);        }        return 0;}

原创粉丝点击