Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

分享一份 二分 + 哈希 的 nlgn 的代码, 670ms

Posted by 354898002 at 2021-06-22 07:36:15 on Problem 1743
#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:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator