Cod sursa(job #3238257)

Utilizator AlinaFloreaFlorea Alina AlinaFlorea Data 23 iulie 2024 16:03:49
Problema Potrivirea sirurilor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.44 kb
#include <fstream>
#include <vector>

using namespace std;

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

string pattern, str;

vector<int> computeLPS(string pattern) {
    int m = pattern.size();
    vector<int> lps(m, 0);
    int i = 1;
    int length = 0;
    while (i < m) {
        if (pattern[i] == pattern[length]) {
            length++;
            lps[i++] = length;
        } else {
            if (length != 0) {
                length = lps[length - 1];
            } else {
                lps[i] = 0;
                i++;
            }
        }
    }
    return lps;    
}

vector <int> searchKMP(string pattern, string str) {
    vector<int>result;
    int n = str.size();
    int m = pattern.size();
    vector<int> lps = computeLPS(pattern);
    int i = 0, j = 0;
    while (i < n) {
        if (str[i] == pattern[j]) {
            i++;
            j++;
        }

        if (j == m) {
            result.push_back(i - j);
            j = lps[j - 1];
        } else {
            if (i < n && str[i] != pattern[j]) {
                if (j == 0) {
                    i++;
                } else {
                    j = lps[j - 1];
                }
            }
        }
    }
    return result;
}



int main() {

    f >> pattern >> str;
    vector<int> result = searchKMP(pattern, str);
    int matches = result.size();
    g << matches << '\n';
    for (int i = 0; i < min(matches, 1000); i++) {
        g << result[i] << " ";
    }

}