Cod sursa(job #756743)

Utilizator mihaipopa12Popa Mihai mihaipopa12 Data 10 iunie 2012 13:30:12
Problema Substr Scor 100
Compilator cpp Status done
Runda Remember Mihai Pătrașcu Marime 1.47 kb
#include<stdio.h>
#include<algorithm>

#define maxN 16500
#define maxLog 17

using namespace std;

FILE*f=fopen("substr.in","r");
FILE*g=fopen("substr.out","w");

int N,k,i,P[maxLog][maxN],cnt,stp,Lcp,best,T[maxN]; char line[maxN];

struct strct{
	int x;
	int y;
	int poz;
}L[maxN];

struct cmp{
	inline bool operator () ( const strct &a, const strct &b ){
		if ( a.x != b.x )
			return a.x < b.x;
		return a.y < b.y;
	}
};

inline int lcp(int x,int y){
	int r = 0;
	if ( x == y ){
		return N - x + 1;
	}
	for ( int k = stp - 1 ; k >= 0 ; --k ){
		if ( P[k][x] == P[k][y] ){
			x += 1<<k; y += 1<<k; r += 1<<k;
		}
	}
	return r;
}

int main () {
	
	fscanf(f,"%d %d\n",&N,&k);
	fgets(line+1,N+1,f);
	
	for ( i = 1 ; i <= N ; ++i ){
		P[0][i] = line[i] - 'a' + 1;
	}
	
	for ( stp = 1, cnt = 1 ; cnt>>1 < N ; ++stp , cnt <<= 1 ){
		for ( i = 1 ; i <= N ; ++i ){
			L[i].x = P[stp-1][i];
			L[i].y = i + (1<<(stp-1)) <= N ? P[stp-1][i+(1<<(stp-1))] : -1;
			L[i].poz = i;
		}
		
		sort( L+1,L+N+1,cmp() );
		
		for ( i = 1 ; i <= N ; ++i ){
			if ( i > 1 && L[i].x == L[i-1].x && L[i].y == L[i-1].y )
				P[stp][L[i].poz] = P[stp][L[i-1].poz];
			else{
				P[stp][L[i].poz] = i;
			}
		}
	}
	
	for ( i = 1 ; i <= N ; ++i ){
		T[ P[stp-1][i] ] = i;
	}
	
	for ( i = 1 ; i <= N - k + 1 ; ++i ){
		if ( ( Lcp = lcp(T[i],T[i+k-1]) ) > best )
			best = Lcp;
	}
	
	fprintf(g,"%d\n",best);
	
	fclose(f);
	fclose(g);
	
	return 0;
}