Cod sursa(job #184373)

Utilizator cretuMusina Rares cretu Data 23 aprilie 2008 16:21:29
Problema Substr Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.63 kb
#include <fstream>
#define MAX 16385
#define MAXLG 15

using namespace std;

int n, k, stp, P[MAX][MAXLG];
string s;

struct state{
    int n1, n2, p;
} L[MAX];

struct cmp{
    bool operator () (state a, state b)
    {
         if (a.n1 == b.n1) return (a.n2 < b.n2);
         return (a.n1 < b.n1);
    }
};

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

int main()
{
    int i, j, x, max = 0;
    ifstream fin("substr.in");
    fin >> n >> k;
    fin >> s;
    fin.close();
    
    for (i = 0; i < n; i++)
        if (s[i] >= '0' && s[i] <= '9') P[i][0] = s[i] - '0';
        else if (s[i] >= 'A' && s[i] <= 'Z') P[i][0] = s[i]-'A'+10;    
             else P[i][0] = s[i]-'a'+36;
    
    for (j = 1; (1 << j) < n; j++)
    {
        for (i = 0; i < n; i++)
        {
            x = i + (1 << (j-1));
            L[i].n1 = P[i][j-1];
            L[i].n2 = x < n ? P[x][j-1] : -1;
            L[i].p = i;    
        }
        sort(L, L+n, cmp());
        for (i = 0; i < n; i++)
            if (i > 0 && L[i].n1 == L[i-1].n1 && L[i].n2 == L[i-1].n2) P[L[i].p][j] = P[L[i-1].p][j];
            else                                                       P[L[i].p][j] = i;;
    }  
    
    stp = j;
    for (i = 0; i <= n-k; i++)
    {
         x = lcp(L[i].p, L[i+k-1].p);
         if (x > max) max = x;
    }
    
    ofstream fout("substr.out");
    fout << max << "\n";
    fout.close();
    
    return 0;
}