Pagini recente » Cod sursa (job #235305) | Cod sursa (job #1118622) | Cod sursa (job #308251) | Cod sursa (job #2036344) | Cod sursa (job #983381)
Cod sursa(job #983381)
#include <iostream>
#include <cstdio>
#include <string>
#include <math.h>
#include <algorithm>
#define MAXN 16384
#define MAXSTEP 20
using namespace std;
int N, k;
char input[MAXN];
struct suffix{
int firstHalf;
int secondHalf;
int poz;
};
suffix L[MAXN];
int P[MAXSTEP][MAXN];
int stp;
bool mycompfunction(const suffix& a, const suffix& b){
if(a.firstHalf == b.firstHalf)
return a.secondHalf < b.secondHalf;
return a.firstHalf < b.firstHalf;
}
void generateSuffixArrays(){
for(int i = 0; i < N; i++){
P[0][i] = input[i] - '0';
}
for(stp = 1; (1 << stp) <= N; stp ++){
int length = 1 << (stp - 1);
for(int i = 0; i < N; i++){
L[i].poz = i;
L[i].firstHalf = P[stp - 1][i];
if(i + length >= N)
L[i].secondHalf = -1;
else
L[i].secondHalf = P[stp - 1][i + length];
}
sort(L, L + N, mycompfunction);
// actualizeaza P
for(int i = 0; i < N; i++){
// same suffix same order number
if( i > 0 && L[i].firstHalf == L[i-1].firstHalf && L[i].secondHalf == L[i - 1].secondHalf)
P[stp][L[i].poz] = P[stp][L[i-1].poz];
else
P[stp][L[i].poz] = i;
}
}
// for(int i = 0; i < N; i++){
// printf("%d ", L[i].poz);
// }
}
int lcp(int x, int y) {
if (x == y)
return N - x;
int res = 0;
for (int i = stp - 1; i >= 0; i--) {
if (P[i][x] == P[i][y]) {
x += 1 << i;
y += 1 << i;
res += 1 << i;
}
}
return res;
}
int longestKAppearingSubstring(){
int maxLength = 0;
for(int i = 0; i < N - k; i++){
int longPref = lcp(L[i].poz, L[i + k - 1].poz);
maxLength = max(maxLength, longPref);
}
return maxLength;
}
int main(){
freopen("substr.in", "r", stdin);
freopen("substr.out", "w", stdout);
scanf("%d %d", &N, &k);
scanf("%s", input);
// printf("%d %d %d", '1', 'a', 'A');
generateSuffixArrays();
int res = longestKAppearingSubstring();
printf("%d\n", res);
return 0;
}