#include #include #include #include #include using namespace std; class KHash { public: KHash(); int Get_Hash(string s); int Shift(int n); protected: vector Base; map cache; }; int KHash::Shift(int n) { return (n >> 1) | ((n & 1) << 30); } int KHash::Get_Hash(string s) { int i; int rv; if (cache.find(s) != cache.end()) return cache[s]; i = s.size(); if (i == 1) return Base[s[0]]; rv = (Base[s[0]] ^ Shift(Base[s[i-1]]) ^ Shift(Get_Hash(s.substr(1, i-1))) ^ Get_Hash(s.substr(0, i-1))); cache[s] = rv; return rv; } 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()); }