Cod sursa(job #1350370)

Utilizator diana97Diana Ghinea diana97 Data 20 februarie 2015 19:33:42
Problema Potrivirea sirurilor Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.03 kb
#include <iostream>
#include <fstream>
#include <cstring>
#include <vector>

using namespace std;

ifstream f ("strmatch.in");
ofstream g ("strmatch.out");

const int B = 127, LMAX = 2000000 + 1;

char text[LMAX], pattern[LMAX];
int P[LMAX];
vector <int> sol;

void citeste() {
    f >> pattern >> text;
}

void build(char *pattern) {
    int k = 0;
    int l = strlen(pattern);

    P[0] = 0;

    for (int i = 1; i < l; i++) {
        while (k > 0 && pattern[k] != pattern[i]) k = P[k - 1];
        if (pattern[i] == pattern[k]) k++;
        P[i] = k;
    }
}

void KMP() {
    build(pattern);
    int l = strlen(text), l2 = strlen(pattern);
    int k = 0;
    for (int i = 0; i < l; i++) {
        while (k > 0 && pattern[k] != text[i]) k = P[k - 1];
        if (pattern[k] == text[i]) k++;
        if(k == l2) sol.push_back(i - l2 + 1);
    }
}

void scrie() {
    int l = sol.size();
    g << l << '\n';
    l = min(l, 1000);
    for (int i = 0; i < l; i++) g << sol[i] << ' ';
}

int main() {
    citeste();
    KMP();
    scrie();
    return 0;
}