Cod sursa(job #2590736)

Utilizator lucametehauDart Monkey lucametehau Data 28 martie 2020 19:42:53
Problema Substr Scor 90
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.63 kb
#include <fstream>
#include <cstring>
#include <algorithm>
#include <deque>

using namespace std;

ifstream cin ("substr.in");
ofstream cout ("substr.out");

struct S {
  int a, b, c;
  bool operator < (const S &other) const {
    return (a == other.a ? (b < other.b) : (a < other.a));
  }
};

int n, k, K;

char s[100005];
int poz[17][100005], ind[100005];
S v[100005];
deque <pair <int, int>> q;

int lcp(int x, int y) {
  int ans = 0;
  if(x == y)
    return n - x + 1;
  for(int i = k - 1; i >= 0; i--) {
    if(poz[i][x] == poz[i][y])
      x += (1 << i), y += (1 << i), ans += (1 << i);
  }
  return ans;
}

int main() {
  cin >> n >> K;
  cin >> (s + 1);
  for(int i = 1; i <= n; i++)
    poz[0][i] = s[i] - 'a';
  for(int i = 1; (1 << (i - 1)) <= n; i++) {
    for(int j = 1; j <= n; j++) {
      v[j].a = poz[i - 1][j];
      v[j].b = (j + (1 << (i - 1)) <= n ? poz[i - 1][j + (1 << (i - 1))] : 0);
      v[j].c = j;
    }
    sort(v + 1, v + n + 1);
    for(int j = 1; j <= n; j++) {
      if(j > 1 && v[j].a == v[j - 1].a && v[j].b == v[j - 1].b)
        poz[i][v[j].c] = poz[i][v[j - 1].c];
      else
        poz[i][v[j].c] = j;
    }
  }
  k = 1;
  while((1 << (k - 1)) <= n)
    k++;
  for(int i = 1; i <= n; i++)
    ind[poz[k - 1][i]] = i;
  int ans = 0;
  for(int i = 2; i <= n; i++) {
    int l = lcp(ind[i - 1], ind[i]);
    while(!q.empty() && q.front().second <= i - K + 1)
      q.pop_front();
    while(!q.empty() && q.back().first >= l)
      q.pop_back();
    q.push_back({l, i});
    if(i >= K)
      ans = max(ans, q.front().first);
  }
  cout << ans;
  return 0;
}