Cod sursa(job #185532)

Utilizator alecmanAchim Ioan Alexandru alecman Data 25 aprilie 2008 16:59:18
Problema Substr Scor 70
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.83 kb
#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 ];

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)
{
  int k, 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()
{
  int i, Pow;

  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);

  int Maxim = -1;
  int T = 0;

  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;
}