Cod sursa(job #1583017)

Utilizator patrutoiuandreipatrutoiu andrei patrutoiuandrei Data 28 ianuarie 2016 17:54:52
Problema Substr Scor 90
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.56 kb
#include <fstream>
#include <algorithm>
#define Ndim 16389
using namespace std;
ifstream fin("substr.in");
ofstream fout("substr.out");
int suffx[23][Ndim],PozSuffx[Ndim],N,K,sol,powr;
char S[Ndim];
struct strct{int st,dr,poz;}L[Ndim];
inline bool cmp(const strct & a, const strct & b)
{
    if(a.st == b.st)
        return a.dr < b.dr;
    return a.st < b.st;
}
void read()
{
    fin>>N>>K>>S+1;
}
void suffix()
{
    int i,k,cnt;
    for(i=1;i<=N;i++)
        suffx[0][i] = S[i]-'a';
    for(powr = 1, cnt = 1; cnt >> 1 <= N; powr++ , cnt <<= 1 )
    {
        for(i=1;i<=N;i++)
        {
            L[i].st = suffx[powr-1][i];
            L[i].dr = i + cnt <=N ? suffx[powr - 1][i + cnt] : -1;
            L[i].poz = i;
        }
        sort(L+1,L+N+1,cmp);
        for(i=1;i<=N;i++)
            suffx[powr][L[i].poz] = i > 1 && L[i].st == L[i-1].st && L[i].dr == L[i-1].dr ? suffx[powr][L[i-1].poz] : i;
    }
    powr--;
}
int LCP(int x,int y)
{
    int k,len = 0;
    if(x == y)
        return N-x;
    for( k = powr; k>=0 && x <= N && y <= N; k--)
    {
        if(suffx[k][x] == suffx[k][y])
        {
            x += (1<<k);
            y += (1<<k);
            len += (1<<k);
        }
    }
    return len;
}
void solve()
{
    int i;
    for(i=1;i<=N;i++)
        PozSuffx[suffx[powr][i]] = i;
    for(i=1;i<=N-K+1;i++)
    {
        sol = max(sol, LCP(PozSuffx[i],PozSuffx[i+K-1]));
    }
}
void print()
{
    fout<<sol;
}
int main()
{
    read();
    suffix();
    solve();
    print();
    return 0;
}