Cod sursa(job #2857359)

Utilizator IoanMihaiIoan Mihai IoanMihai Data 25 februarie 2022 14:26:39
Problema Potrivirea sirurilor Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.15 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin("strmatch.in");
ofstream fout("strmatch.out");
#define NMAX 2000005
int n, m, cnt, nr, lps[NMAX], ans[NMAX];
string pat, txt;
void init_lps()
{
    int len = 0, i = 1;
    lps[0] = 0;
    while(i < n){
        if (pat[i] == pat[len]){
            len ++;
            lps[i] = len;
            i ++;
        }else{
            if (len != 0){
                len = lps[len - 1];
            }else{
                lps[i] = 0;
                i++;
            }
        }
    }
}
int main() {
    getline(fin, pat);
    getline(fin, txt);
    n = pat.size();
    m = txt.size();
    init_lps();
    int i = 0;
    int j = 0;
    while(i < m){
        if (pat[j] == txt[i]){
            i ++;
            j ++;
        }

        if (j == n){
            cnt ++;
            ans[cnt] = i - j;
            j = lps[j - 1];
        }else if (i < m && pat[j] != txt[i]){
            if (j != 0){
                j = lps[j - 1];
            }else{
                i ++;
            }
        }
    }
    fout << cnt << '\n';
    for (int i=1;i<=cnt;i++){
        fout << ans[i] << ' ';
    }
    fout << '\n';
    return 0;
}