#include <iostream> #include <cstring> #define MAX_SIZE 100 using namespace std; class StringHash { public: int size; char *array; char *array_forward; unsigned long long* pre_base; unsigned long long* hash_array; unsigned long long* hash_array_forward; unsigned long long base = 12582917; // 构造函数 StringHash(int size) : size(size) { array = new char[size + 1]; pre_base = new unsigned long long[size + 1]; hash_array = new unsigned long long[size + 1]; std::memset(array, 0, size + 1); std::memset(pre_base, 0, size + 1); std::memset(hash_array, 0, size + 1); } // 析构函数 ~StringHash() { delete[] array; delete[] hash_array; delete[] pre_base; } friend std::istream& operator>>(std::istream& is, StringHash& customStruct) { is.getline(customStruct.array+1, customStruct.size + 1); // Read a line from input stream return is; } friend std::ostream& operator<<(std::ostream& os, const StringHash& customStruct) { os << customStruct.array+1; // Output the array to the output stream return os; } void init() { pre_base[0]=1; for(int i=1;i<=size;i++) pre_base[i]=base*pre_base[i-1]; hash_array[0]=0; for(int i=1;i<=size;i++) { hash_array[i]=hash_array[i-1]*base; hash_array[i]+=array[i]; } } void open_parall() { hash_array_forward = new unsigned long long[size + 1]; array_forward = new char[size + 1]; std::memset(hash_array_forward, 0, size + 1); std::memset(array_forward, 0, size + 1); for(int i=size;i>=1;i--) { array_forward[i]=array[size-i+1]; } for(int i=1;i<=size;i++) { hash_array_forward[i]=hash_array_forward[i-1]*base; hash_array_forward[i]+=array_forward[i]; } } unsigned long long getHash(int l,int r) { return hash_array[r]-hash_array[l-1]*pre_base[r-l+1]; } bool is_paralld(int l,int r) { return getHash(l,r)==getHash(size-r+1,size-l+1,hash_array_forward); } unsigned long long getHash(int l,int r,unsigned long long* Hash) { return Hash[r]-Hash[l-1]*pre_base[r-l+1]; } }; int main() { int desiredSize = 4; // Example size StringHash stringA(desiredSize); cin>>stringA; cout<<stringA<<endl; stringA.init(); stringA.open_parall(); int l,r; while(1) { cin>>l>>r; cout<<stringA.is_paralld(l,r)<<endl; //cout<<stringA.getHash(l,r)<<endl; } // Optionally, you can manipulate the array here return 0; }
标签:std,hash,unsigned,long,板子,哈希,字符串,array,size From: https://www.cnblogs.com/acmLLF/p/18120116