Cod sursa(job #3242728)

Utilizator Her0ninjaDragos Rolland Her0ninja Data 13 septembrie 2024 21:36:21
Problema Potrivirea sirurilor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.54 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;

void LPS(const string& pattern, vector<int>& lps) {
    int hossz=0;
    lps[0]=0;
    int i=1;

    while (i<pattern.size()) {
        if (pattern[i]==pattern[hossz]) {
            hossz++;
            lps[i]=hossz;
            i++;
        } else {
            if (hossz!=0) {
                hossz=lps[hossz-1];
            } else {
                lps[i]=0;
                i++;
            }
        }
    }
}

vector<int> KMP(const string& pattern, const string& text) {
    int M=pattern.size();
    int N=text.size();

    vector<int> lps(M);
    LPS(pattern,lps);

    vector<int> poz;
    int i=0;
    int j=0;

    while (i<N) {
        if (pattern[j] == text[i]) {
            i++;
            j++;
        }

        if (j==M) {
            poz.push_back(i-j);
            j = lps[j-1];
        } else if (i<N&&pattern[j]!=text[i]) {
            if (j!=0) {
                j=lps[j-1];
            } else {
                i++;
            }
        }
    }

    return poz;
}

int main() {
    ifstream f("strmatch.in");
    ofstream g("strmatch.out");
    string A, B;
    getline(f, A);
    getline(f, B);

    vector<int> poz=KMP(A, B);

    int N=poz.size();
    g<<N<<endl;

    int limit=min(N,1000);
    for (int i=0; i<limit;i++) {
        g<<poz[i];
        if (i<limit-1) {
          g<<" ";
        }
    }
    g<< endl;

    f.close();
    g.close();

    return 0;
}