字符串——常用进制hash

以下都只对一个字符串hash,h[n]为该串的hash值

单hash

typedef unsigned long long ULL;

const ULL base = 13131;//2333333
const ULL mod = 1e9+7;
const int maxn = 1e5+50;
ULL h[maxn], p[maxn];
char a[maxn];
int n;

void init(){
    h[0] = 1, p[0] = 0;
    for(int i = 1; i <= n; i++){
        h[i] = h[i-1]*base + a[i] - 'a';
        p[i] = p[i-1]*base;
        /*
        h[i] = ((h[i-1]*base)%mod + a[i]-'a')%mod;
        p[i] = p[i-1]*base;
        */
    }
}

双hash

const ULL base = 13131;//2333333//19260817
const ULL mod1 = 1e9+7, mod2 = 19260817;
const int maxn = 1e5+50;
ULL h1[maxn], p1[maxn], h2[maxn], p2[maxn];
char a[maxn];
int n;

void init(){
    h1[0] = 1, h2[0] = 1, p1[0] = 0, p2[0] = 0;
    for(int i = 1; i <= n; i++){
        h1[i] = (h1[i-1]*base%mod1 + a[i]-'a') % mod1;
        h2[i] = (h2[i-1]*base%mod2 + a[i]-'a') % mod2;
        p1[i] = p1[i-1]*base%mod1
        p2[i] = p2[i-1]*base%mod2;
    }
}

或者用struct存h1和h2

发布了23 篇原创文章 · 获赞 6 · 访问量 829

猜你喜欢

转载自blog.csdn.net/wxy2635618879/article/details/103969899