Cod sursa(job #718595)

Utilizator mihai995mihai995 mihai995 Data 20 martie 2012 21:56:47
Problema Substr Scor 90
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.38 kb
#include <fstream>
#include <algorithm>
using namespace std;

const int N=16385,LG=15,inf=1<<30;
int P[LG][N],ord[N],n;
char s[N];
struct Sort
{
    int a,b,poz;
} list[N];

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

inline bool cmp(const Sort &a,const Sort &b)
{
    return a.a<b.a || a.a==b.a && a.b<b.b;
}

inline bool egal(Sort a,Sort b)
{
    return a.a==b.a && a.b==b.b;
}

void calc(int P[])
{
    for (int i=1,j=0;i<=n;i++)
    {
        if (!egal(list[i],list[i-1]))
            j++;
        P[list[i].poz]=j;
    }
}

void det(int P[])
{
    for (int i=1;i<=n;i++)
        ord[P[i]]=i;
}

void suffix_array()
{
    list[0].a=-inf;
    for (int i=1;i<=n;i++)
        P[0][i]=s[i];
    for (int i=1,step=1;i<LG;i++,step<<=1)
    {
        for (int j=1;j<=n;j++)
            list[j]=(Sort){P[i-1][j],j+step<=n ? P[i-1][j+step] : -1,j};
        sort(list+1,list+n+1,cmp);
        calc(P[i]);
    }
    det(P[LG-1]);
}

int lcs(int x,int y)
{
    int rez=0;
    for (int i=LG-1;i>=0 && x<=n && y<=n;i--)
        if (P[i][x]==P[i][y])
        {
            rez+=1<<i;
            x+=1<<i;
            y+=1<<i;
        }
    return rez;
}

int main()
{
    int rez=0,k;
    in>>n>>k>>s+1;
    suffix_array();
    for (int i=k;i<=n;i++)
        rez=max(rez,lcs(ord[i],ord[i-k+1]));
    out<<rez<<"\n";
    return 0;
}