Cod sursa(job #2465805)

Utilizator Briana_NeaguNeagu Briana Briana_Neagu Data 30 septembrie 2019 21:06:28
Problema Substr Scor 60
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.9 kb
#include <bits/stdc++.h>

using namespace std;

ifstream f("substr.in");
ofstream g("substr.out");

const int nmax = 16384;
int dp[nmax + 5][17];
vector <int> sorted;


int suffix_arrays(string &s, int n)
{
    int stop;
    for (int i = 0; i < n; ++ i)
        dp[i][0] = s[i] - 'a' + 1;

    vector <pair < pair <int, int>, int> > current_suffixes;
    for (int j = 1; (1 << j) < n; ++ j)
    {
        current_suffixes.clear();
        for (int i = 0; i < n; ++ i)
        {
            pair <int, int> compare_pair = {dp[i][j - 1], -1};
            if (i + (1 << (j - 1)) < n)
                compare_pair.second = dp[i + (1 << (j - 1))][j - 1];
            current_suffixes.emplace_back(compare_pair, i);
        }
        sort(current_suffixes.begin(), current_suffixes.end());
        pair <int, int> last = {-1, -1};
        int current_iex = 0;
        for (int i = 0; i < current_suffixes.size(); ++ i)
        {
            if (last == current_suffixes[i].first)
                dp[current_suffixes[i].second][j] = current_iex;
            else
            {
                last = current_suffixes[i].first;
                dp[current_suffixes[i].second][j] = ++ current_iex;
            }
            if ((1 << (j + 1)) >= n)
            {
                sorted.push_back(current_suffixes[i].second);
                stop = j;
            }
        }
    }
    return stop;
}

int lcp(int a, int b, int stop, int n)
{

    int ans = 0;

    for (int j = stop ; j > 0 && a < n && b < n; -- j)
        if ((a + (1 << j) -1 <= n)  && (b + (1 << j) -1 <= n && dp[a][j] == dp[b][j]))
        {
            ans += (1 << j);
            a += (1 << j);
            b += (1 << j);
        }
    return ans;
}

int main()
{
  int n, k;
  f >> n >> k;
  string s;
  f >> s;
  int stop = suffix_arrays(s, n);
  int ans = 0;
  for (int i = 0; i < n - k + 1 ; ++ i)
      ans = max(ans, lcp(sorted[i], sorted[i + k - 1], stop, n));
     g << ans;

}