Cod sursa(job #2223665)

Utilizator caesar2001Stoica Alexandru caesar2001 Data 20 iulie 2018 23:24:50
Problema Substr Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.6 kb
#include <bits/stdc++.h>

using namespace std;
ifstream in("substr.in");
ofstream out("substr.out");

const int NMAX = 16400;
int prefix[16][NMAX], n, k;
string s;

struct Data {
    int x, y, z;
    bool operator< (Data other) const {
        if(x == other.x)
            return y < other.y;
        return x < other.x;
    }
}sol[NMAX];

int lcp(int a, int b, int lim) {
    int ans = 0;
    for(int step = lim; step >= 0; step --) {
        int p = 1 << step;
        if(a + p - 1 <= n && b + p - 1 <= n && prefix[step][a] == prefix[step][b])
            a += p, b += p, ans += p;
    }
    return ans;
}

int main() {
    ios::sync_with_stdio(false);
    in.tie(0);
    out.tie(0);
    in >> n >> k;
    in >> s;
    s = " " + s;
    for(int i = 1; i <= n; i ++)
        prefix[0][i] = s[i] - 'A';
    int i;
    for(i = 1; (1 << (i - 1)) <= n; i ++) {
        int step = 1 << (i - 1);
        for(int j = 1; j <= n; j ++) {
            sol[j].x = prefix[i - 1][j];
            if(j + step <= n)
                sol[j].y = prefix[i - 1][j + step];
            else
                sol[j].y = INT_MIN;
            sol[j].z = j;
        }
        sort(sol + 1, sol + n + 1);
        for(int j = 1; j <= n; j ++) {
            if(sol[j].x == sol[j - 1].x && sol[j].y == sol[j - 1].y)
                prefix[i][sol[j].z] = prefix[i][sol[j -1].z];
            else
                prefix[i][sol[j].z] = j;
        }
    }
    int ans = 0;
    for(int j = 1; j <= n - k + 1; j ++)
        ans = max(ans, lcp(sol[j].z, sol[j + k - 1].z, i));
    out << ans;
    return 0;
}