Cod sursa(job #2488519)

Utilizator Horia14Horia Banciu Horia14 Data 6 noiembrie 2019 23:53:36
Problema Potrivirea sirurilor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.16 kb
#include<fstream>
#include<iostream>
#define MAX_LEN 2000000
#define MAX_POS 1000
using namespace std;

string P, T;
int pi[MAX_LEN + 1];
int pos[MAX_POS], n, m, nrp;

void readString(string name_fin) {
    ifstream fin(name_fin);
    fin >> P >> T;
    n = T.size();
    m = P.size();
    fin.close();
}

void buildPrefix() {
    int i, k = 0;
    pi[0] = 0;
    for(i = 1; i < m; i++) {
        while(k > 0 && P[i] != P[k])
            k = pi[k - 1];
        if(P[i] == P[k])
            k++;
        pi[i] = k;
    }
}

void KMP() {
    int i, k = 0;
    for(i = 0; i < n; i++) {
        while(k > 0 && T[i] != P[k])
            k = pi[k - 1];
        if(T[i] == P[k])
            k++;
        if(k == m) {
            if(nrp < MAX_POS)
                pos[nrp++] = i - m + 1;
            else nrp++;
        }
    }
}

void printOccurences(string name_fout) {
    int l, i;
    ofstream fout(name_fout);
    l = min(MAX_POS, nrp);
    fout << nrp << "\n";
    for(i = 0; i < l; i++)
        fout << pos[i] << " ";
    fout << "\n";
    fout.close();
}

int main() {
    readString("strmatch.in");
    buildPrefix();
    KMP();
    printOccurences("strmatch.out");
    return 0;
}