Cod sursa(job #2017264)

Utilizator mouse_wirelessMouse Wireless mouse_wireless Data 31 august 2017 17:48:28
Problema Substr Scor 30
Compilator cpp Status done
Runda Teme Pregatire ACM Unibuc 2013 Marime 1.72 kb
#include <cstdio>
#include <cmath>
#include <vector>
#include <algorithm>
#include <cassert>
#include <cstring>
#include <climits>
#include <queue>
#include <ctime>
using namespace std;
typedef long long LL;

#ifdef INFOARENA
#define ProblemName "substr"
#endif

#define MCONCAT(A, B) A B
#ifdef ProblemName
#define InFile MCONCAT(ProblemName, ".in")
#define OuFile MCONCAT(ProblemName, ".out")
#else
#define InFile "fis.in"
#define OuFile "fis.out"
#endif

typedef unsigned int elem;

const int MAXN = 17000;
char buf[MAXN];
int N, M, K;
elem h[MAXN], pw[MAXN];
const int B = 29;

void prec() {
  pw[0] = 1;
  for (int i = 1; i <= N; ++i)
    pw[i] = pw[i - 1] * B;
  h[0] = buf[0] - 'a';
  for (int i = 1; i < N; ++i)
    h[i] = h[i - 1] * B + buf[i] - 'a';
}

inline elem getHash(int r, int L) {
  int l = r - L + 1;
  if (l <= 0)
    return h[r];
  return h[r] - h[l - 1] * pw[L];
}

inline bool eqAt(int i, int j) {
  return getHash(i, M) == getHash(j, M);
}

int nrapp(int j) {
  int ans = 0;
  for (int i = M - 1; i < N; ++i)
  if (eqAt(i, j))
    ++ans;
  return ans;
}

bool canDo() {
  int best = 0;
  for (int j = M - 1; j < N; ++j) {
    int cand = nrapp(j);
    if (cand > best)
      best = cand;
  }
  return (best >= K);
}

int binSrch() {
  int left = 1, right = N;
  int found = 0;
  while (left <= right) {
    M = left + (right - left) / 2;
    if (canDo()) {
      found = M;
      left = M + 1;
    }
    else
      right = M - 1;
  }
  return found;
}

int main() {
  assert(freopen(InFile, "r", stdin));
  assert(freopen(OuFile, "w", stdout));
  scanf("%d%d", &N, &K);
  scanf("%s", buf);
  prec();
  printf("%d\n", binSrch());
  return 0;
}