Cod sursa(job #1025505)

Utilizator ericptsStavarache Petru Eric ericpts Data 10 noiembrie 2013 09:57:40
Problema Prefix Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 0.97 kb
#include <cstdio>

using namespace std;

const int MAX_N = int(1e6) + 100;

char str[MAX_N];
int len;

int phi[MAX_N];

void KMP(){
    int now,i;
    now = 0;
    phi[0] = -1;
    for(i = 1 ; str[i] ;) {
        if(str[i] == str[now]){
            phi[i] = now;
            ++i;
            ++now;
        } else if(phi[now] != -1) {
            now = phi[now];
        } else {
            now = 0;
            phi[i] = now;
            ++i;
        }
    }
    len = i;
}

int main()
{
    freopen("prefix.in", "r", stdin);
    freopen("prefix.out", "w", stdout);
    int T;
    scanf("%d", &T);
    while(T > 0){
        scanf("%s\n", str);
        KMP();
        int i;

        for(i = len - 1 ; i > 0 ; --i) {
            if(phi[i] == 0 && str[i] != str[0])
                continue;
            const int start = i - phi[i];
            if((i + 1) % start == 0)
                break;
        }
        if(i)
            ++i;
        printf("%d\n", i);
        --T;
    }
    return 0;
}