Cod sursa(job #420619)

Utilizator ssergiussSergiu-Ioan Ungur ssergiuss Data 20 martie 2010 08:55:19
Problema Substr Scor 80
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.73 kb
#include <algorithm>
#include <fstream>

using namespace std;

#define Input "substr.in"
#define Output "substr.out"

#define Dim 16384 + 5
#define Log 14 + 5

struct entry {

    int p;
    int nr[2];
};

char A[Dim];
int N, K, Sol, P[Log][Dim];
int aux[Dim];
entry L[Dim];

struct cmp {

    bool operator()( const entry &a, const entry &b ) {

        return (a.nr[0] < b.nr[0]) || (a.nr[0] == b.nr[0] && a.nr[1] < b.nr[1]);
    }
};

int lcp( int x, int y, const int &stp ) {

    int k, sol;

    sol = 0;
    for( k = stp; k >= 0 && x < N && y < N; --k )
        if( P[k][x] == P[k][y] ) {

            x += 1 << k;
            y += 1 << k;
            sol += 1 << k;
        }

    return sol;
}

int main() {

    ifstream fin( Input );
    ofstream fout( Output );

    int i, cnt, stp;

    fin >> N >> K;
    fin.ignore( 1, 'n' );
    fin.getline( A, Dim );

    for( i = 0; i < N; ++i )
        P[0][i] = A[i] - '0';
    for( cnt = stp = 1; cnt >> 1 < N; cnt <<= 1, ++stp ) {

        for( i = 0; i < N; ++i ) {

            L[i].nr[0] = P[stp - 1][i];
            if( i + cnt < N )
                L[i].nr[1] = P[stp - 1][i + cnt];
            else
                L[i].nr[1] = -1;
            L[i].p = i;
        }

        sort( L, L + N, cmp() );
        for( i = 0; i < N; ++i )
            if( i > 0 && L[i].nr[0] == L[i - 1].nr[0] && L[i].nr[1] == L[i - 1].nr[1] )
                P[stp][L[i].p] = P[stp][L[i - 1].p];
            else
                P[stp][L[i].p] = i;
    }

    Sol = 0;
    for( i = 0; i + K < N; ++i )
        Sol = max( Sol, lcp( L[i].p, L[i + K - 1].p, stp - 1 ) );

    fout << Sol;

    fin.close();
    fout.close();

    return 0;
}