Cod sursa(job #1258906)

Utilizator gabrieligabrieli gabrieli Data 9 noiembrie 2014 15:54:14
Problema Potrivirea sirurilor Scor 14
Compilator cpp Status done
Runda Arhiva educationala Marime 1.96 kb
#include <cmath>
#include <cstdint>
#include <fstream>
#include <string>
#include <vector>
using namespace std;

constexpr uint64_t M1 = 15485863;
constexpr uint64_t M2 = 15485867;
constexpr uint64_t B = 128;

inline uint64_t hashf(const string& text, const uint64_t base, const uint64_t m);

struct StringHash{
    uint64_t base;
    uint64_t base_pow_length;
    uint64_t m;
    size_t length;
    
    StringHash(uint64_t base, uint64_t m, uint64_t length) : base(base), m(m), length(length) {
        base_pow_length = pow(base, length);
    }
    
    uint64_t operator()(const string& text) const {
        uint64_t result = 0;
        for (char c : text)
            result = ((result * base) % m + c) % m;
        return result;
    }
    
    uint64_t rehash(uint64_t old_h, char c_significant, char c_new) const {
        return ((old_h * base) % m + m - (c_significant * base_pow_length) % m + c_new) % m;
    }
};

int main() {
    ifstream fin("strmatch.in");
    ofstream fout("strmatch.out");
    
    string query, text;
    fin >> query >> text;
    
    if (query.size() > text.size()) {
        fout << "0\n";
        return 0;
    }
    
    StringHash hash1(B, M1, query.size()), hash2(B, M2, query.size());
    
    size_t matches = 0;
    vector<size_t> positions;
    
    uint64_t HQ1 = hash1(query);
    uint64_t HQ2 = hash2(query);
    
    size_t i = 0;
    uint64_t h1 = hash1(text.substr(0, query.size()));
    uint64_t h2 = hash2(text.substr(0, query.size()));
    
    while (true) {
        if (h1 == HQ1 && h2 == HQ2) {
            matches++;
            if (matches <= 1000) positions.push_back(i);
        }
        
        if (i + query.size() < text.size()) {
            h1 = hash1.rehash(h1, text[i], text[i + query.size()]);
            h2 = hash2.rehash(h2, text[i], text[i + query.size()]);
            i++;
        }
        else break;
    }
     
    fout << matches << '\n';
    for (size_t p : positions) fout << p << ' ';
    fout << endl;
    
    return 0;
}