Cod sursa(job #2001930)

Utilizator richieYRichie Yeung richieY Data 18 iulie 2017 02:36:51
Problema Prefix Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.19 kb
#include <iostream>
#include <fstream>
#include <string>
#include <vector>

using namespace std;

ifstream fin("prefix.in");
ofstream fout("prefix.out");
int main() {
    int t;
    string pat;
    fin >> t;
    for (int a = 0; a < t; a += 1) {
        fin >> pat;
        int n = pat.length();
        vector<int> p(n);

        p[0] = 0;
        int l = 0;
        
        int longestPrefix = 0;
        
        for (int i = 1; i < n; i += 1) {
            while (l > 0 && pat[i] != pat[l]) l = p[l-1];
            if (pat[i] == pat[l]) l += 1;
            p[i] = l;
            
            if (l*2 - 1 == i) {
                longestPrefix = l;
            }
        }
        
        if (longestPrefix == 0) {
            fout << 0 << '\n';
            continue;
        }
        
        int x = longestPrefix * 2;
        int y = 0;
        int ans = longestPrefix*2;
        while (pat[y] == pat[x]) {
            if (y == longestPrefix-1) {
                ans += longestPrefix;
                y = 0;
            } else {
                y += 1;
            }
            x += 1;
        }
        
        fout << ans << '\n';
    }
    return 0;
}