Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "stdafx.h"
- #include <iostream>
- #include <string>
- #include <math.h>
- #include <fstream>
- using namespace std;
- const int ALF = 256;
- const int Q = 9551;
- int Hash(string text, int n)
- {
- int h = 0;
- for (int i = 0; i<n; i++)
- {
- h = (ALF * h + (unsigned char)text[i]) % Q;
- }
- return h;
- }
- bool Check(string text, string wzor, int pozycja)
- {
- for (int i = 0; i < wzor.length(); i++)
- if (wzor[i] != text[pozycja + i])
- return false;
- return true;
- }
- int Last(int n)
- {
- int l = 1;
- for (int i = 1; i <= n - 1; i++)
- {
- l = (ALF*l) % Q;
- }
- return l;
- }
- void Szukaj(string wzor, string text)
- {
- int t = Hash(text, wzor.length());
- int p = Hash(wzor, wzor.length());
- int pozycja = 0;
- int d = Last(wzor.length());
- for (int i = wzor.length(); i <= text.length(); i++)
- {
- pozycja = i - wzor.length();
- if (p == t && Check(text, wzor, pozycja))
- {
- cout << pozycja << " ";
- }
- t = (t + Q - (d * (unsigned char)text[i - wzor.length()]) % Q) % Q;
- t = (t * ALF + (unsigned char)text[i]) % Q;
- }
- cout << endl;
- }
- void Read()
- {
- int liczba_przypadkow;
- string file;
- string wzor;
- string linia;
- string text;
- cin >> liczba_przypadkow;
- for (int i = 0; i < liczba_przypadkow; i++)
- {
- cin >> file;
- cin.ignore();
- getline(cin, wzor);
- fstream plik;
- plik.open(file, ios::out | ios::in);
- while (getline(plik, linia))
- {
- text = text + linia + "\n";
- }
- plik.close();
- Szukaj(wzor, text);
- text.clear();
- }
- }
- int main()
- {
- Read();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement