Cod sursa(job #2098158)

Utilizator mariusn01Marius Nicoli mariusn01 Data 2 ianuarie 2018 14:42:43
Problema Substr Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.85 kb
#include <fstream>
#include <iostream>
#include <algorithm>

using namespace std;

char s[17000];
struct structura {
    int first;
    int second;
    int poz;
};
structura L[17000];
int P[17000];
int a[18][170000];

int n, k, maxim, sol, Log, x, y;
int cmp(structura a, structura b) {
    if (a.first != b.first)
        return a.first < b.first;
    else
        return a.second < b.second;
}

int main () {
    ifstream fin ("substr.in");
    ofstream fout("substr.out");

    fin>>n>>k>>s+1;
    Log = 0;
    while ((1 << Log) <= n)
        Log++; /// 2^Log > n

    for (int i=1;i<=n;i++) {
        L[i].first = s[i];
        L[i].second = -1;
        L[i].poz = i;
    }


    for (int lg = 0; lg <= Log; lg++) {
        sort(L+1, L+n+1, cmp);

        a[lg][ L[1].poz ] = 1;
        for (int i=2;i<=n;i++)
            if (L[i].first == L[i-1].first && L[i].second == L[i-1].second)
                a[lg][ L[i].poz ] = a[lg][ L[i-1].poz ];
            else
                a[lg][ L[i].poz ] = 1 + a[lg][ L[i-1].poz ];



        for (int i=1;i<=n;i++) {
            L[i].poz = i;
            L[i].first = a[lg][i];
            if (i + (1<<lg) <= n)
                L[i].second = a[lg][i+(1<<lg)];
            else
                L[i].second = -1;
        }




    }

    for (int i=1;i<=n;i++) {
        P[a[Log][i]] = i;
    }


    for (int i=1;i+k-1<=n;i++) {
        x = P[i];
        y = P[i+k-1];
        if (x == y)
            sol = n-x+1;
        else {
            sol = 0;
            for (int lg = Log; lg >= 0 && x <= n && y<=n; lg--)
                if (a[lg][x] == a[lg][y]) {
                    x+=(1<<lg);
                    y+=(1<<lg);
                    sol+=(1<<lg);
                }
            }
        maxim = max(maxim, sol);
    }
    fout<<maxim;
    return 0;
}