Cod sursa(job #1636087)

Utilizator sulzandreiandrei sulzandrei Data 6 martie 2016 22:17:22
Problema Potrivirea sirurilor Scor 18
Compilator cpp Status done
Runda Arhiva educationala Marime 1.26 kb
#include <iostream>
#include <fstream>
#include <unordered_map>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
ifstream in("strmatch.in");
ofstream out("strmatch.out");
unordered_map<char,int> number;
string T,P;
vector< int > positions;
int d = 256,q = 14107,h;
void Rabin_Karp()
{
    int n = T.length();
    int m = P.length();
    int h = 1 , p = 0 , ts = 0;
    for(int i = 0;  i < m -1 ; i ++)
        h = (h*d) % q;
    for(int i = 0 ; i < m ; i++)
        p = ( d* p + P[i]) % q,
        ts = (d * ts + T[i]) % q;
    for(int s = 0 ; s <= n-m  ; s++)
    {
        if (p == ts)
        {
            bool ok  = true;
            for(int i = 0 ; i < m ;  i ++)
                if (P[i] != T[s+i])
                    ok = false;
            if(ok)
                positions.push_back(s);
        }
        if(s < n-m)
        {
            ts = ( d *(ts - T[s] * h)  + T[ s + m ] ) % q;
            while( ts < 0)
                ts = ts +q;
        }
    }
}
int main()
{
    in >> P >> T;
    Rabin_Karp();
    out<<positions.size()<<'\n';
    int i=0;
    for(auto it = positions.begin() ; i < min(1000,(int)positions.size()) && it != positions.end(); it++,i++)
        out<<*it<<'\n';
    return 0;
}