Pagini recente » Cod sursa (job #2002598) | Cod sursa (job #821845) | Cod sursa (job #1619552) | Clasament tema_1_10f | Cod sursa (job #185535)
Cod sursa(job #185535)
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define INPUT "substr.in"
#define OUTPUT "substr.out"
#define NMAX 16386
#define LGMAX 16
typedef struct Str
{
int x; int y; int p;
};
Str L[ NMAX ], Ord[ NMAX ];
int N, K, Step;
char Sir[ NMAX ];
int P[ LGMAX ][ NMAX ];
int i, Pow, k, ret, Maxim, T;
void ReadValues()
{
char c;
scanf("%d %d", &N, &K);
scanf("%c", &c);
fgets(Sir, NMAX, stdin);
}
inline bool cmp(Str X, Str Y)
{
return (X.x == Y.x) ? (X.y < Y.y ) : (X.x < Y.x);
}
inline bool cmp2(Str X, Str Y)
{
return X.x < Y.x;
}
int LCP(int X, int Y)
{
ret = 0;
if(X == Y) return N - X;
for(k = Step - 1; k >= 0 && X < N && Y < N; --k)
if(P[ k ][ X ] == P[ k ][ Y ])
X += 1 << k, Y += 1 << k, ret += 1 << k;
return ret;
}
void CreateArray()
{
Maxim = -1;
T = 0;
for(i = 0; i < N; ++i)
P[ 0 ][ i ] = Sir[ i ] - '0';
for(Step = 1, Pow = 1; (Pow >> 1) < N; ++Step, Pow <<= 1)
{
for(i = 0; i < N; ++i)
{
L[ i ].x = P[ Step - 1 ][ i ];
L[ i ].y = (i + Pow < N) ? P[ Step - 1 ][ i + Pow ] : -1;
L[ i ].p = i;
}
sort(L, L + N, cmp);
for(i = 0; i < N; ++i)
P[ Step ][ L[ i ].p ] = (i > 0 && L[ i ].x == L[ i - 1 ].x && L[ i ].y == L[ i - 1 ].y) ? P[ Step ][ L[ i - 1].p ] : i;
}
for(i = 0; i < N; ++i)
{
Ord[ i ].x = P[ Step - 1 ][ i ];
Ord[ i ].y = -1;
Ord[ i ].p = i;
}
sort(Ord, Ord + N, cmp2);
for(i = 0; i < N - K; ++i)
{
T = LCP( Ord[ i ].p, Ord[ i + K - 1].p );
if(T > Maxim )
Maxim = T;
}
printf("%d\n", Maxim);
}
int main()
{
freopen(INPUT, "r", stdin); freopen(OUTPUT, "w", stdout);
ReadValues();
CreateArray();
fclose(stdin); fclose(stdout);
return 0;
}