Cod sursa(job #1710742)

Utilizator andrei.mermezeAndrei Mermeze andrei.mermeze Data 29 mai 2016 18:45:13
Problema Potrivirea sirurilor Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.44 kb
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
void PrefixFunction(const std::string& str, std::vector<int>& prefix){
    int i, j;
    j = 0;
    prefix[0] = 0;
    for (i = 1; i < (int)prefix.size(); i++) {
        while (j > 0 && str[j] != str[i]) {
            j = prefix[j - 1];
        }

        if (str[i] == str[j]) {
            j++;
        }
        prefix[i] = j;
    }
}

void KMP(const std::string& str, const std::string& word){
    int i, j;
    int count;
    i = 0;
    j = 0;
    std::vector<int> prefix(str.size());
    std::vector<int> matches(1000);
    int k;

    count = 0;
    k = 0;
    std::ofstream g("strmatch.out");
    PrefixFunction(word, prefix);


    while (i < (int)str.size()) {
        while(str[i] == word[j] && j < (int)word.size() && i < (int)str.size()){
            i++;
            j++;
        }
        if(j == (int)word.size()){
            count++;
            if(k < 1000) {
                matches[k++] = i - j;
            }
            j = prefix[j-1];
        } else {
            if (j > 0){
                j = prefix[j - 1];
            } else {
                i++;
            }
        }
    }

    g << count << std::endl;
    for(i = 0; i < k; i++){
        g << matches[i] << " ";
    }
}


int main(){
    std::string str;
    std::string word;

    std::ifstream f("strmatch.in");
    std::getline(f,word);
    std::getline(f,str);
    f.close();

    KMP(str, word);

    return 0;
}