Cod sursa(job #1127985)

Utilizator 2dorTudor Ciurca 2dor Data 27 februarie 2014 14:38:13
Problema Potrivirea sirurilor Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.42 kb
#include <iostream>
#include <fstream>
#include <cstring>
#include <vector>
using namespace std;

ifstream fin("strmatch.in");
ofstream fout("strmatch.out");

const int RADIX = 125;
const int MAXLEN = 2000005;

string pattern, text;
int patternLength, textLength;
int DFA[MAXLEN][RADIX];
vector<int> Sol;

void Read() {
    fin >> pattern;
    patternLength = pattern.length();
    fin >> text;
    textLength = text.length();
}

void BuildDFA() {
    int X = 0;
    DFA[0][pattern[0]] = 1;
    for (int i = 1; i <= patternLength; ++i) {
        for (int c = '0'; c <= 'z'; ++c)
            DFA[i][c] = DFA[X][c];//copy mismatch cases
        if (i == patternLength) continue;
        DFA[i][pattern[i]] = i + 1;//equality case
        X = DFA[X][pattern[i]];//update X
    }
}

void KMP() {
    int X = 0;//the state in which we are
    for (int c = 0; c < textLength; ++c) {
        X = DFA[X][text[c]];
        if (Sol.size() < 1000 && X == patternLength)
            Sol.push_back(c - patternLength + 1);
    }
}

void Write() {
    fout << Sol.size() << '\n';
    for (int it = 0; it < min((int)Sol.size(), 1000); ++it)
        fout << Sol[it] << ' ';
}

int main() {
    Read();
    cerr << "Data read.\n";
    BuildDFA();
    cerr << "DFA built.\n";
    KMP();
    cerr << "KMP done.\n";
    Write();
    cerr << "Data written.\n";
    fin.close();
    fout.close();
    return 0;
}