#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; }; int KHash::Shift(int n) { return (n >> 1) | ((n & 1) << 30); } int KHash::Get_Hash(string s) { int start, size, i; cache.resize(s.size()); for (i = 0; i < cache.size(); i++) cache[i].resize(s.size()+1, -1); for (size = 1; size <= s.size(); size++) { for (start = 0; start+size <= s.size(); start++) { if (size == 1) { cache[start][size] = Base[s[start]]; } else { cache[start][size] = (Base[s[start]] ^ Shift(Base[s[start+size-1]]) ^ Shift(cache[start+1][size-1]) ^ cache[start][size-1]); } } } return cache[0][s.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()); }