#include #include #include #include using namespace std; class KHash { public: KHash(); int Get_Hash(string s); int Get_Hash_DP(int start, int size); int Shift(int n); protected: vector Base; vector < vector > cache; string S; }; int KHash::Shift(int n) { return (n >> 1) | ((n & 1) << 30); } int KHash::Get_Hash(string s) { int i; S = s; cache.resize(s.size()); for (i = 0; i < cache.size(); i++) cache[i].resize(s.size()+1, -1); return Get_Hash_DP(0, s.size()); } int KHash::Get_Hash_DP(int start, int size) { if (size == 1) return Base[S[start]]; if (cache[start][size] != -1) return cache[start][size]; cache[start][size] = (Base[S[start]] ^ Shift(Base[S[start+size-1]]) ^ Shift(Get_Hash_DP(start+1, size-1)) ^ Get_Hash_DP(start, size-1)); // printf("%3d %3d %x\n", start, size, cache[start][size]); return cache[start][size]; } KHash::KHash() { int i; srand48(10); for (i = 0; i < 256; i++) Base.push_back(lrand48()); } int main(int argc, char **argv) { KHash *D; string s; int i; D = new KHash(); if (argc != 2) { cerr << "Usage: khash word\n"; exit(1); } s = argv[1]; printf("%08x %s\n", D->Get_Hash(s), s.c_str()); }