Cod sursa(job #2322206)

Utilizator alexge50alexX AleX alexge50 Data 17 ianuarie 2019 16:13:47
Problema Potrivirea sirurilor Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.22 kb
/*
 *  Software sellers want to divide the users and conquer them, making each
 *  user agree not to share with others.
 *     - Richard Stallman
 */

#include <iostream>
#include <fstream>
#include <regex>

int main()
{
    std::ifstream fin("strmatch.in");
    std::string pattern;
    std::string text;

    fin >> pattern >> text;

    pattern = ' ' + pattern;
    text = ' ' + text;

    std::vector<int> pi;
    std::vector<int> matches;
    int allMatches;
    pi.insert(pi.begin(), text.size(), {});

    int lc = 0;
    for(int i = 2; i < text.size(); i++)
    {
        while(lc > 0 && text[i] != pattern[lc + 1])
            lc = pi[lc];
        if(text[i] == pattern[lc + 1])
            lc++;
        pi[i] = lc;
    }

    allMatches = 0;
    lc = 0;
    for(int i = 1; i < text.size(); i++)
    {
        while(lc > 0 && text[i] != pattern[lc + 1])
            lc = pi[lc];
        if(text[i] == pattern[lc + 1])
            lc++;
        if(lc == pattern.size() - 1)
        {
            allMatches++;
            matches.push_back(i - static_cast<int>(pattern.size()) + 1);
        }
    }

    std::ofstream fout("strmatch.out");
    fout << allMatches << std::endl;
    for(int p: matches)
        fout << p << " ";

    return 0;
}