| ||||||||||
| Online Judge | Problem Set | Authors | Online Contests | User | ||||||
|---|---|---|---|---|---|---|---|---|---|---|
| Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest | |||||||||
分享一份 二分 + 哈希 的 nlgn 的代码, 670ms#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
using namespace std;
int seq[20000];
typedef unsigned long long uint64_t;
uint64_t seed = 10000007;
uint64_t pow_seed[20001];
struct Node {
uint64_t hash;
int pos;
int next;
}node_pool[20000];
int top;
int head[20000];
bool find(uint64_t hash, int pos, int n, int c) {
int slot = hash % n;
for (int i = head[slot]; i != -1; i = node_pool[i].next) {
if (node_pool[i].hash == hash && node_pool[i].pos + c < pos) {
return true;
}
}
return false;
}
void insert(uint64_t hash, int pos, int n) {
int slot = hash % n;
node_pool[top].hash = hash;
node_pool[top].pos = pos;
node_pool[top].next = head[slot];
head[slot] = top++;
}
bool check(int *seq, int n, int c) {
memset(head, -1, sizeof(int)*n);
top = 0;
uint64_t hash = 0;
for (int i = 0; i < n; i++) {
(hash *= seed) += seq[i];
if (i >= c) {
hash -= seq[i-c] * pow_seed[c];
if (find(hash, i, n, c)) {
return true;
}
insert(hash, i, n);
}
}
return false;
}
int main() {
pow_seed[0] = 1;
for (int i = 1; i <= 10000; i++) {
pow_seed[i] = pow_seed[i-1]*seed;
}
int n;
while (scanf("%d", &n) != EOF && n != 0) {
for (int i = 0; i < n; i++) {
scanf("%d", seq + i);
}
for (int i = n-1; i >= 1; i--) {
seq[i] -= seq[i-1];
}
int L = 3, R = n/2;
while (L <= R) {
int mid = (L+R) >> 1;
if (check(seq, n, mid)) {
L = mid+1;
} else {
R = mid-1;
}
}
printf("%d\n", L < 4 ? 0 : L);
}
return 0;
}
Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator