Cod sursa(job #1073966)

Utilizator andrei31Andrei Datcu andrei31 Data 6 ianuarie 2014 23:13:32
Problema Potrivirea sirurilor Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.26 kb
#include <vector>
#include <string>
#include <fstream>
#include <algorithm>

std::vector<int>  computeTable(const std::string &s){

   std::vector<int> result(s.length() + 1);
   result[0] = -1;
   result[1] = 0;

   for (int i = 1; i < s.length(); ++i){
        result[i + 1] = result[i] + 1;
        while (result[i + 1] > 0 && s[result[i + 1] - 1] != s[i])
            result[i + 1] = result[result[i + 1] - 1] + 1;
   }

   return result;
}

void KMP(const std::string &w, const std::string &s, const std::vector<int> t){
    //il caut pe w in s

    std::vector<int> solutions;

    for (int m = 0, i = 0; m < s.length();){

        if (i == w.length())
            solutions.push_back(m);
        else
            if (s[m + i] == w[i]){
                ++i;
                continue;
            }
        m += i - t[i];
        i = std::max(0, t[i]);
    }

    std::ofstream fout("strmatch.out");

    fout << solutions.size() << std::endl;
    for (int i = 0; i < std::min(1000, (int)solutions.size()); ++i)
        fout << solutions[i] << " ";
    fout << std::endl;
}

int main(){

    std::ifstream fin("strmatch.in");

    std::string w, s;

    std::getline(fin, w);
    std::getline(fin, s);

    std::vector<int> table(computeTable(w));
    KMP(w, s, table);
    return 0;
}