CODE:
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #define BASE 177 #define MAX 20010 using namespace std; struct HashSet{ static const int mo = 9997; int head[mo + 100],total; int next[MAX],pos[MAX]; unsigned long long true_hash[MAX]; void Clear() { memset(head,0,sizeof(head)); total = 0; } bool Insert(unsigned long long hash,int _pos,int ans) { int x = hash % mo; for(int i = head[x];i;i = next[i]) if(true_hash[i] == hash && _pos - pos[i] > ans) return true; next[++total] = head[x]; true_hash[total] = hash; pos[total] = _pos; head[x] = total; return false; } }map; unsigned long long p[MAX]; unsigned long long hash[MAX]; int cnt; int _src[MAX],src[MAX]; void Pretreatment(); inline bool Judge(int ans); int main() { Pretreatment(); while(scanf("%d",&cnt),cnt) { for(int i = 1;i <= cnt; ++i) scanf("%d",&_src[i]); for(int i = 1;i < cnt; ++i) src[i] = _src[i + 1] - _src[i] + 88; hash[0] = 0; for(int i = 1;i < cnt; ++i) hash[i] = hash[i - 1] * BASE + src[i]; int l = 0,r = cnt,ans = 0; while(l <= r) { int mid = (l + r) >> 1; if(Judge(mid)) l = mid + 1,ans = mid; else r = mid - 1; } ans++; if(ans < 5) ans = 0; printf("%d\n",ans); } return 0; } void Pretreatment() { p[0] = 1; for(int i = 1;i < MAX; ++i) p[i] = p[i - 1] * BASE; } inline bool Judge(int ans) { map.Clear(); for(int i = ans;i < cnt; ++i) if(map.Insert((unsigned long long)hash[i] - hash[i - ans] * p[ans],i,ans)) return true; return false; }
POJ 1743 Musical Theme Hash+二分
原文地址:http://blog.csdn.net/jiangyuze831/article/details/40040375