Cod sursa(job #999839)

Utilizator danalex97Dan H Alexandru danalex97 Data 21 septembrie 2013 15:47:16
Problema Substr Scor 90
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.67 kb
#include <fstream>
#include <cstring>
#include <algorithm>
using namespace std;

ifstream F("substr.in");
ofstream G("substr.out");

const int Nmax = 17000;
const int Lmax = 20;

typedef struct { int a,b,p; } three;

three make_three(int a,int b,int c)
{
    three t;
    t.a=a;
    t.b=b;
    t.p=c;
    return t;
}

bool three_cmp(three a,three b)
{
    return a.a < b.a || ( a.a == b.a && a.b < b.b );
}

int N,K,lng;
int P[Lmax][Nmax];
char C[Nmax];

three T[Nmax];

bool cmp_poz(int a,int b)
{
    return P[lng][a] < P[lng][b];
}

int poz[Nmax];

int lcp(int a,int b)
{
    int steps=lng,lung=0;
    while ( steps-- )
    {
        if ( a >= N || b >= N ) break;
        if ( P[steps][a] == P[steps][b] )
        {
            int now = 1<<steps;
            lung += now, a += now, b += now;
        }
    }
    return lung;
}

int main()
{
    F>>N>>K, F.get(), F>>C;
    for (int i=0;i<N;++i)
        P[0][i] = C[i]-'a';

    for (int l=1,j=1;(j>>1)<N;++l,j<<=1)
    {
        lng = l;
        for (int i=0;i<N;++i)
        {
            T[i].a = P[l-1][i];
            T[i].b = -1;
            if ( i+j < N ) T[i].b = P[l-1][i+j];
            T[i].p = i;
        }
        sort(T,T+N,three_cmp);
        for (int i=0;i<N;++i)
        {
            P[l][T[i].p] = i;
            if ( i>0 )
                if ( T[i].a == T[i-1].a && T[i].b == T[i-1].b )
                    P[l][T[i].p] = P[l][T[i-1].p];
        }
    }

    for (int i=0;i<N;++i)
        poz[i] = i;
    sort(poz,poz+N,cmp_poz);

    int out = 0;
    for (int i=K-1,j=0;i<N;++i,++j)
        out = max(out,lcp(poz[i],poz[j]));
    G<<out<<'\n';
}