Cod sursa(job #1655765)

Utilizator smaraldaSmaranda Dinu smaralda Data 18 martie 2016 12:14:24
Problema Substr Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 2 kb
#include<stdio.h>
#include<algorithm>
#include<vector>
using namespace std;

const int NMAX = 17000, LOG = 15;

struct TYPE {
    pair <int, int> p;
    int ind;

} aux[NMAX];

vector < pair <int, int> > suf;

int ord[LOG][NMAX];

bool cmp (TYPE a, TYPE b) {
    return a.p < b.p;
}

int n, k, step;
char s[NMAX];

int lcp (int x, int y) {
    if(x == y)
        return n - x;

    int k, ans = 0;
    for(k = step - 1; k >= 0 && x < n && y < n; -- k)
        if(ord[k][x] == ord[k][y]) {
            x += (1 << k);
            y += (1 << k);
            ans += (1 << k);
        }
    return ans;
}

int main() {
    freopen("substr.in", "r", stdin);
    freopen("substr.out", "w", stdout);
    int len, x, y, i, left, right, sol;

    scanf("%d%d%s", &n, &k, s);

    for(i = 0; i < n; ++ i)
        ord[0][i] = s[i] - 'a';

    step = 1;
    while(1 << (step - 1) < n) {
        for(i = 0; i < n; ++ i) {
            x = ord[step - 1][i];
            if(i + (1 << (step - 1)) < n)
                y = ord[step - 1][i + (1 << (step - 1))];
            else
                y = -1;

            aux[i].p = make_pair(x, y);
            aux[i].ind = i;
        }

        sort(aux, aux + n, cmp);

        for(i = 0; i < n; ++ i)
            if(i > 0 && aux[i].p == aux[i - 1].p)
                ord[step][aux[i].ind] = ord[step][aux[i - 1].ind];
            else
                ord[step][aux[i].ind] = i;

        ++ step;
    }

    for(i = 0; i < n; ++ i)
        suf.push_back(make_pair(ord[step - 1][i], i));

    sort(suf.begin(), suf.end());

    //for(i = 0; i < n; ++ i)
  //      fprintf(stderr, "%s\n", s + suf[i].second);
    left = 0;
    for(right = 0; right < suf.size(); ++ right) {
        while(lcp(suf[right].second, suf[left].second) == 0 || right - left + 1 > k)
            ++ left;

        if(right - left + 1 >= k)
            sol = max(sol, lcp(suf[right].second, suf[left].second));
    }

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