Cod sursa(job #883001)

Utilizator dicu_dariaDaria Dicu dicu_daria Data 19 februarie 2013 17:21:13
Problema Substr Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.69 kb
#include <fstream>
#include <iostream>
#include <algorithm>
#include <cstring>

using namespace std;

int i, n, step, x, sol, k, nr, P[20][20010];
string s;
typedef struct
{
    int x, y, p;
} elem;

elem a[20010];

bool cmp(elem a, elem b)
{
    return ((a.x == b.x) ? (a.y < b.y) : (a.x < b.x));
}

bool cmp2(elem a, elem b)
{
    return a.x < b.x;
}

int lcp(int x, int y)
{
    int sol = 0;
    for(step = 1, k = 0; step < n; k++, step <<= 1);
    for(; x < n and y < n and step; step >>= 1, k--)
        if(P[k][x] == P[k][y])
        {
            x += 1<<k;
            y += 1<<k;
            sol += min(step, n);
        }
    return sol;
}

int main()
{
    ifstream fi("substr.in");
    ofstream fo("substr.out");
    fi >> n >> nr >> s;
    for(i = 0; i < n; i++) P[0][i] = s[i] - '0';
    //construiesc p[k][i] - ordinea subsirului i...2^k - 1
    for(k = 1, step = 1; step >> 1 <= n; step <<= 1, k++)
    {
        for(i = 0; i < n; i++) //construiesc un sir din i... 2^(k-1) - 1, i + 2^k
        {
            a[i].x = P[k-1][i];
            if(i+step >= n) a[i].y = -1; else a[i].y = P[k-1][i+step];
            a[i].p = i;
        }
        sort(a, a+n, cmp);
        for(i = 0; i < n; i++)
            if(i and a[i-1].x == a[i].x and a[i-1].y == a[i].y) P[k][a[i].p] = P[k][a[i-1].p];
            else P[k][a[i].p] = i;
    }

    for(step = 1, k = 0; step < n; k++, step <<= 1);
    for(i = 0; i < n; i++)
    {
        a[i].x = P[k][i];
        a[i].p = i;
    }
    sort(a+1, a+n, cmp2);
    for(i = 0; i < n-nr; i++)
    {
        x = lcp(a[i].p, a[i+nr-1].p);
        if(x > sol) sol = x;
    }
    fo << sol << "\n";
    return 0;
}