Cod sursa(job #2326783)

Utilizator DavidLDavid Lauran DavidL Data 23 ianuarie 2019 23:09:20
Problema Substr Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.76 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fi("substr.in");
ofstream fo("substr.out");

const int NMAX = 20005;
const int LOG = 20;

struct boss
{
    int ord[2], poz;
};

bool operator <(const boss &a, const boss &b)
{
    if (a.ord[0] != b.ord[0])
        return a.ord[0] < b.ord[0];
    return a.ord[1] < b.ord[1];
}

int n, K;
char A[NMAX];
int P[LOG][NMAX];
boss L[NMAX];
int pas, cnt;
pair <int, int> V[NMAX];

int lcp(int a, int b)
{
    int put = 17, ret = 0;

    while (put >= 0)
    {
        if (a + (1 << put) <= n + 1 && b + (1 << put) <= n + 1 && P[put][a] == P[put][b])
        {
            a += (1 << put);
            b += (1 << put);
            ret += (1 << put);
        }
        put--;
    }
    return ret;
}

void getSuffixArray()
{
    for (int i = 1; i <= n; i++)
        P[0][i] = A[i] - '0';

    for (pas = 1, cnt = 1; (pas >> 1) < n; cnt++, pas <<= 1)
    {
        for (int i = 1; i <= n; i++)
        {
            L[i].ord[0] = P[cnt - 1][i];
            L[i].ord[1] = i + pas <= n ? P[cnt - 1][i + pas] : -1;
            L[i].poz = i;
        }
        sort(L + 1, L + n + 1);

        for (int i = 1; i <= n; i++)
        {
            if (i > 1 && L[i].ord[0] == L[i - 1].ord[0] && L[i].ord[1] == L[i - 1].ord[1])
                P[cnt][L[i].poz] = P[cnt][L[i - 1].poz];
            else
                P[cnt][L[i].poz] = i;
        }
    }
    cnt--;
}

int main()
{
    fi >> n >> K >> A + 1;

    getSuffixArray();

    for (int i = 1; i <= n; i++)
        V[i] = {P[cnt][i], i};

    sort(V + 1, V + n + 1);

    int rez = 0;
    for (int i = 1; i + K - 1 <= n; i++)
        rez = max(rez, lcp(V[i].second, V[i + K - 1].second));

    fo << rez;

    return 0;
}