Cod sursa(job #1226041)

Utilizator popoiu.georgeGeorge Popoiu popoiu.george Data 4 septembrie 2014 14:05:05
Problema Substr Scor 100
Compilator cpp Status done
Runda Teme Pregatire ACM Unibuc 2013 Marime 1.98 kb
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <bitset>
#include <stack>
#include <queue>
#include <list>
#include <map>
#include <set>

using namespace std;

#define INFL "substr.in"
#define OUTFL "substr.out"

#define nmax 17010
#define mmax 15

struct elem {
    int nr[2];
    int p;

    bool operator < (const elem& o) const {
        return nr[0] == o.nr[0] ? nr[1] < o.nr[1] : nr[0] < o.nr[0];
    }
} L[nmax];

int n, m, k;
int P[mmax][nmax], v[nmax];
char s[nmax];

void read() {
    scanf("%d%d", &n, &k);
    scanf("%s", s);
}

int lcp(int x, int y) {
    int ans = 0;

    if(x == y)
        return n-x;

    for(int i=m; i>=0 && x<n && y<n; --i)
        if(P[i][x] == P[i][y]) {
            ans += (1<<i);
            x += (1<<i);
            y += (1<<i);
        }

    return ans;
}

void solve() {
    for(int i=0; i<n; ++i)
        if(s[i] >= '0' && s[i] <= '9')
            P[0][i] = s[i] - '0';
        else if(s[i] >= 'A' && s[i] <= 'Z')
            P[0][i] = (s[i] - 'A') + 10;
        else
            P[0][i] = (s[i] - 'a') + 36;

    int step;
    for(step=1; 1<<(step-1) < n; ++step) {
        for(int i=0; i<n; ++i) {
            L[i].nr[0] = P[step-1][i];
            L[i].nr[1] = i + (1<<(step-1)) < n ? P[step-1][i + (1<<(step-1))] : -1;
            L[i].p = i;
        }

        sort(L, L+n);

        for(int i=0; i<n; ++i)
            P[step][L[i].p] = i > 0 && L[i].nr[0] == L[i-1].nr[0] && L[i].nr[1] == L[i-1].nr[1] ? P[step][L[i-1].p] : i;
    }

    m = --step;

    for(int i=0; i<n; ++i)
        v[P[m][i]] = i;

    int ans = 0;
    for(int i=0; i+k<=n; ++i)
        ans = max(ans, lcp(v[i], v[i+k-1]));

    printf("%d", ans);
}

int main() {
//#define ONLINE_JUDGE 1
#ifndef ONLINE_JUDGE
	freopen(INFL, "r", stdin);
	freopen(OUTFL, "w", stdout);
#endif

	read();
	solve();

	return 0;
}