Cod sursa(job #1254282)

Utilizator blue_phoenixPosea Elena blue_phoenix Data 2 noiembrie 2014 14:43:53
Problema Prefix Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 0.75 kb
#include <iostream>
#include <fstream>
#include <cstring>
#define NMAX 1000005
using namespace std;


int main() {
	ifstream fin("prefix.in");
	ofstream fout("prefix.out");
	int T;
	fin >> T;
	char *text = new char[NMAX];
	int n;
	int *fail = new int[NMAX];
	while (T--) {
		fin >> (text+1);
		n = strlen(text + 1);
		// compute fail function
		fail[1] = 0;
		int i; // poz in sir
		int k = 0; // cat de lung e cel mai lung prefix care e si sufix..
		for (int i = 2; i <= n; i++) {
			while (k > 0 && text[k + 1] != text[i]) {
				k = fail[k - 1];
			}
			if (text[k + 1] == text[i]) {
				k++;
			}
			fail[i] = k;
		}
		for(i = n;i >= 1; i--)
			if(fail[i] && (i % (i-fail[i]) == 0)) {
				fout << i << "\n";
				break;
			}
		if(i == 0) fout << "0\n";
	}
	
	return 0;
}