Cod sursa(job #355798)

Utilizator toni2007Pripoae Teodor Anton toni2007 Data 12 octombrie 2009 10:55:52
Problema Substr Scor 40
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.23 kb
#include <stdio.h>
#include <algorithm>

using namespace std;

#define maxN    20000
#define x       first
#define y       second

pair < pair <int, int>, int > L[maxN];
int N, K, P[15][maxN], step;
char s[maxN];

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

int main () {
    int i, cnt, sol = 0;

    freopen("substr.in", "r", stdin);
    freopen("substr.out", "w", stdout);

    scanf("%d%d\n", &N, &K);
    gets(s);

    for (i = 0; i < N; ++ i)
        P[0][i] = s[i] - 'a';

    for (step = 1, cnt = 1; cnt >> 1 < N; ++ step, cnt <<= 1) {
        for (i = 0; i < N; ++ i) {
            L[i].x.x = P[step - 1][i];
            L[i].x.y = i + cnt < N ? P[step - 1][i + cnt] : - 1;
            L[i].y = i;
        }

        sort(L, L + N);

        for (i = 0; i < N; ++ i)
            P[step][L[i].y] = i > 0 && L[i].x.x == L[i - 1].x.x &&
                              L[i].x.y == L[i - 1].x.y ? P[step][L[i - 1].y] : i;
    }


    for (i = K - 1; i < N; ++ i)
        sol = max(sol, lcp(L[i - K + 1].y, L[i].y));

    printf("%d\n", sol);
    return 0;
            
}