Cod sursa(job #2519014)

Utilizator mihneacazCazacu Mihnea mihneacaz Data 6 ianuarie 2020 21:39:39
Problema Substr Scor 90
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.75 kb
#include <fstream>
#include <vector>
#include <algorithm>
#include <string>

using namespace std;

const int NMAX = 16500;
const int LOG = 20;

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

int dp[NMAX][LOG];
int sa[NMAX];

void suffix_array(string &s, int n)
{
    vector < pair < pair <int, int>, int > > v;
    for(int i = 0; i < n; ++i)
        dp[i][0] = s[i] - 'a' + 1;
    for(int j = 1; (1 << j) < n; ++j) {
        v.clear();
        for(int i = 0; i < n; ++i) {
            int poz = i + (1 << (j - 1));
            if(poz <= n)
                v.push_back({{dp[i][j - 1], dp[poz][j - 1]}, i});
            else
                v.push_back({{dp[i][j - 1], -1}, i});
        }
        sort(v.begin(), v.end());
        int c = 1;
        int cnt = 0;
        for (int i = 0; i <(int) v.size(); ++i) {
            if (i > 0 && v[i].first == v[i - 1].first)
                dp[v[i].second][j] = c;
            else
                dp[v[i].second][j] = ++c;
            sa[++cnt] = v[i].second;
        }
    }
}


int lcp(int x, int y, int n, int lg)
{
    int ans = 0;
    for(int bit = lg; bit >= 0 && x <= n && y <= n; --bit) {
        if(x + (1 << bit) - 1 > n)
            continue;
        if(y + (1 << bit) - 1 > n)
            continue;
        if(dp[x][bit] == dp[y][bit]) {
            x = x + (1 << bit);
            y = y + (1 << bit);
            ans = ans + (1 << bit);
        }
    }
    return ans;
}

int main() {
    int n, k;
    string s;
    cin >> n >> k;
    cin >> s;
    int lg = 1;
    for( ; (1 << lg) <= n; ++lg);
    lg--;
    suffix_array(s, n);
    int ans = 0;
    for(int i = 0; i < n - k + 1; ++i) {
        ans = max(ans, lcp(sa[i], sa[i + k - 1], n, lg));
    }
    if(ans > n)
        ans = n;
    cout << ans << "\n";
    return 0;
}