POJ 1200 Crazy Search (RKhash)

題目鏈接:http://poj.org/problem?id=1200


RKhash 把每個子串轉爲nc進制再hash

RKhash 詳解:http://www.cnblogs.com/cobbliu/archive/2012/05/24/2517151.html

#include <cstdio>
#include <cstring>

const int N = 16666666;
bool hash[N];
int letr[26];
char s[N];

int pow(int a, int b)
{
    int r = 1, base = a;
    while(b) {
        if(b & 1) r *= base;
        base *= base;
        b >>= 1;
    }
    return r;
}

int main()
{
    int n, nc, t = 0;
    while(~scanf("%d%d", &n, &nc)) {
        memset(hash, 0, sizeof(hash));
        memset(letr, 0, sizeof(letr));
        scanf("%s", s);
        int len = strlen(s), pw = pow(nc, n-1), ans = 0;
        for(int i = 0, j = 0; i < len && j != nc; i++) {
            if(!letr[s[i]-'a']) letr[s[i]-'a'] = j++;
        }
        for(int i = 0; i < n - 1; i++) t = t * nc + letr[s[i] - 'a'];
        for(int i = n - 1; i < len; i++) {
            t = t * nc + letr[s[i] - 'a'];
            if(!hash[t]) {
                hash[t] = 1;
                ans++;
            }
            t = t - pw * letr[s[i-n+1] - 'a'];
        }
        printf("%d\n", ans);
    }
    return 0;
}




發佈了40 篇原創文章 · 獲贊 4 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章