Cod sursa(job #1944152)

Utilizator gapdanPopescu George gapdan Data 28 martie 2017 22:55:16
Problema Substr Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.48 kb
#include <cstdio>
#include <algorithm>
#define maxN 16500
#define maxcnt 16

using namespace std;

struct nod
{
    int nr1,nr2,pos;
}L[maxN];
bool cmp(const nod &a,const nod &b)
{
    if(a.nr1==b.nr1)
        return a.nr2<b.nr2;
    return a.nr1<b.nr1;
}
char str[maxN];
int P[maxcnt][maxN]; ///suffix array
int n,i,j,len,cnt,k,sol;

void build_suffixArray()
{
    int i,j;
    for(i=0;i<len;i++)
        P[0][i]=str[i];
    for(cnt=1;(1<<cnt)<len;cnt++)
    {
        for(j=0;j<len;j++)
        {
            L[j].pos=j;
            L[j].nr1=P[cnt-1][j];
            if(j + (1<<cnt-1) < len)
                L[j].nr2=P[cnt-1][j + (1<<cnt-1)];
            else L[j].nr2=-1;
        }
        sort(L,L+len,cmp);
        for(j=0;j<len;j++)
            if(j && L[j].nr1==L[j-1].nr1 && L[j].nr2==L[j-1].nr2)
                P[cnt][L[j].pos]=P[cnt][L[j-1].pos];
            else P[cnt][L[j].pos]=j;
    }
    --cnt;
}
int lcp(int x,int y)
{
    int p,res=0;
    if(x==y)
        return len-x;
    for(p=cnt-1; p >= 0 && x < len && y < len; --p)
        if(P[p][x] == P[p][y]){
            res += (1<<p);
            x += (1<<p);
            y += (1<<p);
        }
    return res;
}

int main()
{
    freopen("substr.in","r",stdin);
    freopen("substr.out","w",stdout);
    scanf("%d %d\n",&len,&k);
    gets(str);
    build_suffixArray();
    for(i=0;i<len-k;i++)
        sol=max(sol,lcp(L[i].pos,L[i+k-1].pos));
    printf("%d",sol);
    return 0;
}