soj 3014: Seek the Name, Seek the Fame (字符串hash)

@(K ACMer)

题意:
对于一个字符串s,找出所有相同的前缀后缀长度.
分析:
一看就可以用字符串hash来搞,首位两端维护一个hash值,如果该hash值相等就说明字符串相同.

字符串hash代码

#include <cstdio>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <algorithm>
using namespace std;
const int maxn = 4e5 + 123, INF = 0x3fffffff, mod = 1e9 + 7;
typedef int ull;
char s[maxn];
int slen, seed = 131;

int main(void ){
    while (~scanf("%s", s)) {
        slen = (int)strlen(s);
        ull a = 0, b = 0, x = 1;
        bool first = false;
        for (int i = 0, j = slen - 1; i < slen; i++, j--) {
            a = (s[i] - 'a' + 1) + a * seed;
            b = b + (s[j] - 'a' + 1) * x;
            if (a == b) {
                if (first) printf(" ");
                else first = true;
                printf("%d", i + 1);
            }
            x *= seed;
        }
        printf("\n");
    }
    return 0;
}

你可能感兴趣的:(hash)