Cod sursa(job #2805742)

Utilizator Langa_bLanga Radu Langa_b Data 21 noiembrie 2021 21:17:01
Problema Potrivirea sirurilor Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2 kb
#include <fstream>
#include <vector>
#include <string>
#define baza 73
#define mod1 100007
#define mod2 100021
using namespace std;
ifstream cin("strmatch.in");
ofstream cout("strmatch.out");
long long hash1 = 0, hash2 = 0, p1, p2, cnt;
vector<int> rez;
string str1, str2;
int main() {
	cin >> str1;
	cin.get();
	cin >> str2;
	p1 = 1;
	p2 = 1;
	for (long long i = 0; i < str1.size(); i++) {
		long long charact = 0;
		if (str1[i] >= '0' && str1[i] <= '9') {
			charact = str1[i] - 48;
		}
		else {
			charact = str1[i] - 55;
		}
		hash1 = (hash1 * baza + charact) % mod1;
		hash2 = (hash2 * baza + charact) % mod2;
		if (i != 0) {
			p1 = (p1 * baza) % mod1;
			p2 = (p2 * baza) % mod2;
		}
	}
	if (str1.size() > str2.size()) {
		cout << 0;
		return 0;
	}
	else {
		long long nh1 = 0, nh2 = 0;
		long long l1 = str1.size(), l2 = str2.size();
		for (long long i = 0; i < str1.size(); i++) {
			long long charact = 0;
			if (str2[i] >= '0' && str2[i] <= '9') {
				charact = str2[i] - 48;
			}
			else {
				charact = str2[i] - 55;
			}
			nh1 = (nh1 * baza + charact) % mod1;
			nh2 = (nh2 * baza + charact) % mod2;
			if (nh1 == hash1 && nh2 == hash2) {
				cnt++;
				rez.emplace_back(0);
			}
			
		}
		for (long long i = str1.size(); i < str2.size(); i++) {
			long long charact = 0;
			if (str2[i] >= '0' && str2[i] <= '9') {
				charact = str2[i] - 48;
			}
			else {
				charact = str2[i] - 55;
			}
			long long charact2 = 0, ind2 = i - l1;
			if (str2[ind2] >= '0' && str2[ind2] <= '9') {
				charact2 = str2[ind2] - 48;
			}
			else {
				charact2 = str2[ind2] - 55;
			}
			nh1 = ((((nh1 - charact2 * p1) % mod1 + mod1) % mod1) * baza + charact) % mod1;
			nh2 = ((((nh2 - charact2 * p2) % mod2 + mod2) % mod2) * baza + charact) % mod2;
			if (nh1 == hash1 && nh2 == hash2) {
				cnt++;
				rez.emplace_back(ind2 + 1);
			}
		}
		cout << cnt<<'\n';
		for (long long i = 0; i < rez.size(); i++) {
			if (i < 1000) {
				cout << rez[i] << ' ';
			}
		}
	}
}