Pagini recente » Cod sursa (job #1838286) | Cod sursa (job #1728509) | Istoria paginii runda/test12321321 | Cod sursa (job #415642) | Cod sursa (job #796884)
Cod sursa(job #796884)
#include <iostream>
#include <fstream>
#include <vector>
#include <cmath>
using namespace std;
const int hash_base = 101;
int init_hash(string s) {
int hash = 0;
int base = 1;
for(int i = s.length()-1; i >= 0; i--) {
hash += base * (int)s[i];
base *= hash_base;
}
return hash;
}
int roll_hash(int oldv, int hash, int newv, int exp) {
hash -= oldv*pow(hash_base, exp-1);
hash *= hash_base;
hash += newv;
return hash;
}
int main() {
string A, B;
ifstream in("strmatch.in");
in >> A >> B;
in.close();
cerr << A;
vector<int> poz;
int nr_matches = 0;
int N = B.length();
int M = A.length();
int a_hash = init_hash(A);
int sub_hash = init_hash(B.substr(0, M));
cout << "a: " << a_hash << endl;
cout << "b: " << sub_hash << endl;
for(int i = 0; i < N - M + 1; i++) {
if(a_hash == sub_hash)
if(B.compare(i, M, A) == 0) {
nr_matches++;
if(nr_matches <= 1000)
poz.push_back(i);
}
sub_hash = roll_hash((int)B[i], sub_hash, (int)B[i+M], M);
}
ofstream out("strmatch.out");
out << nr_matches << endl;
for(int i = 0; i < poz.size(); i++)
out << poz[i] << " ";
out.close();
return 0;
}