Cod sursa(job #3242649)

Utilizator UengineDavid Enachescu Uengine Data 12 septembrie 2024 21:52:57
Problema Potrivirea sirurilor Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.2 kb
#include <fstream>
#include <string>
#include <vector>

using namespace std;

const int d = 26; ///number of existing characters
const int MOD = 660013;

ifstream cin("strmatch.in");
ofstream cout("strmatch.out");

string pat, txt;
vector <int> pos;

void search(){
    int N = txt.size(), M = pat.size();
    int pat_hash = 0, text_hash = 0;
    int h = 1;

    for (int i = 0; i < M - 1; i++)
        h = (h * d) % MOD;

    for (int i = 0; i < M; i++){
        pat_hash = (d * pat_hash + pat[i]) % MOD;
        text_hash = (d * text_hash + txt[i]) % MOD;
    }

    for (int i = 0; i <= N - M; i++){
        if (pat_hash == text_hash){
            bool ok = 1;
            for (int j = 0; j < M and ok; j++)
                if (txt[i + j] != pat[j])
                    ok = 0;
            if (ok)
                pos.push_back(i);
        }
        if (i < N - M){
            text_hash = (d * (text_hash - txt[i] * h) + txt[i + M]) % MOD;
            if (text_hash < 0)
                text_hash = (text_hash + MOD);
        }
    }
}

int main()
{
    cin >> pat >> txt;
    search();
    cout << pos.size() << '\n';
    for(int i = 0; i < min(1000, (int)pos.size()); i++)
        cout << pos[i] << ' ';
    return 0;
}