Pagini recente » Cod sursa (job #905441) | Cod sursa (job #2082239) | Cod sursa (job #550395) | Cod sursa (job #621977) | Cod sursa (job #799297)
Cod sursa(job #799297)
#include <iostream>
#include <fstream>
#include <vector>
#include <cmath>
using namespace std;
const unsigned long long hash_base = 7;
unsigned long long init_hash(string s) {
unsigned long long hash = 0;
unsigned long long base = 1;
for(int i = s.length() - 1;i >= 0; i--) {
hash += (int)(s[i] -'A' + 1);
}
return hash;
}
unsigned long long roll_hash(int oldv, unsigned long long hash, int newv, int exp) {
hash -= oldv;
hash += newv;
return hash;
}
int main() {
string A, B;
ifstream in("strmatch.in");
in >> A >> B;
in.close();
vector<int> poz;
int nr_matches = 0;
int N = B.length();
int M = A.length();
unsigned long long a_hash = init_hash(A);
unsigned long long sub_hash = init_hash(B.substr(0, M));
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]-'A'+1), sub_hash, (int)(B[i+M]-'A'+1), M);
}
ofstream out("strmatch.out");
out << nr_matches << endl;
for(int i = 0; i < poz.size(); i++)
out << poz[i] << " ";
out.close();
return 0;
}