Cod sursa(job #1666445)

Utilizator vladrochianVlad Rochian vladrochian Data 28 martie 2016 00:49:40
Problema Substr Scor 90
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.22 kb
#include <algorithm>
#include <cstring>
#include <fstream>

using namespace std;

const int N_MAX = 16384;
const int LOG_MAX = 14;

int N, K;
char a[N_MAX + 5];

pair<pair<int, int>, int> c[N_MAX + 5];
int p[LOG_MAX + 2][2 * N_MAX + 5];

int ans;

void BuildSuffixArray() {
   memset(p, -1, sizeof p);

   for (int i = 0; i < N; ++i)
      p[0][i] = a[i] - 'a';

   for (int i = 0; i < LOG_MAX; ++i) {
      for (int j = 0; j < N; ++j) {
         c[j].first = make_pair(p[i][j], p[i][j + (1 << i)]);
         c[j].second = j;
      }
      sort(c, c + N);
      for (int j = 1; j < N; ++j)
         p[i + 1][c[j].second] = p[i + 1][c[j - 1].second] + (c[j].first != c[j - 1].first);
   }
}

int LongestCommonPrefix(int x, int y) {
   int ans = 0;
   for (int i = LOG_MAX; i >= 0; --i)
      if (p[i][x] == p[i][y]) {
         ans |= 1 << i;
         x += 1 << i;
         y += 1 << i;
      }
   return ans;
}

void Solve() {
   for (int i = 0; i < N - K + 1; ++i)
      ans = max(ans, LongestCommonPrefix(c[i].second, c[i + K - 1].second));
}

int main() {
   ifstream("substr.in") >> N >> K >> a;
   BuildSuffixArray();
   Solve();
   ofstream("substr.out") << ans << "\n";
   return 0;
}