Cod sursa(job #2790825)

Utilizator Alex_tz307Lorintz Alexandru Alex_tz307 Data 29 octombrie 2021 16:46:32
Problema Substr Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.53 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin("substr.in");
ofstream fout("substr.out");

const int kSigma = 1 << 6;
const int kN = 1 << 14;
const int base = 98317;
const int mod = 805306457;
int n, k, a[kN], p[kN];
string s;
unordered_map<int, int> f;

void add_self(int &x, const int &y) {
  x += y;
  if (x >= mod) {
    x -= mod;
  }
}

int add(int x, const int &y) {
  add_self(x, y);
  return x;
}

void sub_self(int &x, const int &y) {
  x -= y;
  if (x < 0) {
    x += mod;
  }
}

int mul(const int &x, const int &y) {
  return (int64_t)x * y % mod;
}

bool check(int len) {
  int h = 0;
  for (int i = 0; i < len; ++i) {
    h = add(mul(h, base), a[i]);
  }
  f.clear();
  ++f[h];
  for (int i = len; i < n; ++i) {
    sub_self(h, mul(a[i - len], p[len - 1]));
    h = add(mul(h, base), a[i]);
    if (++f[h] == k) {
      return true;
    }
  }
  return false;
}

void TestCase() {
  fin >> n >> k >> s;
  if (k == 1) {
    fout << n << '\n';
    return;
  }
  for (int i = 0; i < n; ++i) {
    a[i] = (int)s[i];
  }
  p[0] = 1;
  for (int i = 1; i < n - k + 1; ++i) {
    p[i] = mul(p[i - 1], base);
  }
  int l = 1, r = n - k + 1, ans = 0;
  while (l <= r) {
    int mid = (l + r) >> 1;
    if (check(mid)) {
      ans = mid;
      l = mid + 1;
    } else {
      r = mid - 1;
    }
  }
  fout << ans << '\n';
}

int main() {
  int tests = 1;
  for (int tc = 1; tc <= tests; ++tc) {
    TestCase();
  }
  fin.close();
  fout.close();
  return 0;
}