Pagini recente » Cod sursa (job #2529738) | Cod sursa (job #462266) | Cod sursa (job #1783022) | Cod sursa (job #2420497) | Cod sursa (job #514280)
Cod sursa(job #514280)
#include <stdio.h>
#include <algorithm>
using namespace std;
#define NMAX 17000
struct xyp{
int x, y, p;};
struct comp{
bool operator()(const xyp &a, const xyp &b){
if(a.x == b.x) return a.y < b.y;
return a.x < b.x;
}
};
xyp P[NMAX];
char S[NMAX];
int A[16][NMAX];
int n, k;
int lcp(int x, int y){
int step = 0;
for(; (1<<step) <= n; ++step); --step;
int sol = 0;
for(int j = step; j >= 0; --j)
if(x + (1<<j) -1 <= n && y + (1<<j) -1 <= n && A[j][x] == A[j][y])
sol += (1<<j), x += (1<<j), y += (1<<j);
return sol;
}
void suffix_array(){
for(int i = 1; i <= n; ++i)
A[0][i] = S[i] -'a';
int lung = 0;
for(int j = 1; (1<<(j-1)) <= n; ++j){
lung = j;
for(int i = 1; i <= n; ++i){
P[i].x = A[j-1][i];
P[i].y = i + (1<<(j-1)) > n ? -1 : A[j-1][i+(1<<(j-1))];
P[i].p = i;
}
int p = 0;
sort( P + 1, P + n + 1, comp());
for(int i = 1; i <= n; ++i)
if(i > 1 && P[i-1].x == P[i].x && P[i-1].y == P[i].y)
A[j][P[i].p] = p;
else A[j][P[i].p] = ++p;
}
}
int main(){
freopen("substr.in", "r", stdin);
freopen("substr.out" ,"w", stdout);
scanf("%d%d\n", &n, &k);
fgets(S + 1, NMAX, stdin);
suffix_array();
int sol = 0;
for(int i = 1; i <= n-k+1; ++i)
sol = max(lcp(P[i].p, P[i+k-1].p), sol);
printf("%d\n", sol);
return 0;
}