Cod sursa(job #761810)

Utilizator valentin.harsanValentin Harsan valentin.harsan Data 27 iunie 2012 15:05:00
Problema Substr Scor 90
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.32 kb
#include<fstream>
#include<algorithm>
using namespace std;

ifstream in("substr.in");
ofstream out("substr.out");

const int N = 16390;

struct el {
	int x, y, p;
};

int n, k, sol = 0, p[20][N], stp;
el l[N];
char a[N];

bool cmp(const el &a, const el &o) {
	if(o.x == a.x)
		return a.y < o.y;
	return a.x < o.x;
}

void suff_array() {
	int i, cnt;
	
	for(i = 0; i!=n; ++i)
		p[0][i] = a[i] - '0';
	for(stp = 1, cnt = 1; (cnt>>1) < n; ++stp, cnt<<=1) {
		
		for(i = 0; i!=n; ++i) {
			l[i].x = p[stp - 1][i];
			l[i].p = i;
			
			if(i + cnt < n)
				l[i].y = p[stp - 1][i + cnt];
			else
				l[i].y = -1;
		}
		sort(l, l + n, cmp);
		
		for(i = 0; i!=n; ++i) {
			if(l[i - 1].x == l[i].x && l[i - 1].y == l[i].y)
				p[stp][l[i].p] = p[stp][l[i - 1].p];
			else
				p[stp][l[i].p] = i;
		}
	}
	--stp;
}

int lcp(int x, int y) {
	int k, rez = 0;
	if(x == y)
		return n - y;
	
	for(k = stp; k>=0 && x < n && y < n; --k) {
		if(x + (1<<k) > n || y + (1<<k) > n)
			continue;
		
		if(p[k][x] == p[k][y]) {
			x += 1<<k; y += 1<<k;
			rez += 1<<k;
		}
	}
	return rez;
}

int main() {
	
	in >> n >> k;
	in.get();
	
	in.getline(a, N);
	
	suff_array();
	
	for(int i = 0; i<=n - k + 1; ++i)
		sol = max(sol, lcp(l[i].p, l[i + k - 1].p));
	
	out << sol << "\n";
	
	return 0;
}