Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #include <vector>
- using namespace std;
- const int MOD = 70000;
- int powmod(int n, int p, int q) {
- if (p == 0)
- return 1;
- return (powmod(n, p - 1, q) * n) % q;
- }
- int hashgen(string s, int a, int b, int q) {
- int x = 2;
- int res = 0;
- int n = b - a;
- for (int i = 0; i < n; ++ i) {
- res = ((res % q) + ((s[a + i] % q) * ((powmod(x, n - i - 1, q) % q)) % q)) % q;
- }
- return res;
- }
- int rehash(string s, int oldhash, int oldc, int newc, int q) {
- int x = 2;
- int step = newc - oldc - 1;
- int newhash = oldhash;
- int d1 = ((s[oldc] % q) * powmod(x, step, q)) % q;
- while (newhash < d1) newhash += q;
- newhash = (newhash - d1) % q;
- newhash = (newhash * (x % q)) % q;
- newhash = (newhash + (s[newc] % q)) % q;
- return newhash;
- }
- int RB(string s, string t) {
- // s = t
- // t = p
- int n = s.size();
- int m = t.size();
- int hashs = hashgen(s, 0, m, MOD);
- int hasht = hashgen(t, 0, m, MOD);
- for (int i = 0; i <= n - m; ++ i) {
- if (hashs == hasht) {
- int j = 0;
- for (; j < m && t[j] == s[i + j]; ++ j);
- if (j == m)
- return i;
- }
- if (i < n - m)
- hashs = rehash(s, hashs, i, i + m, MOD);
- }
- return -1;
- }
- int BM(string s, string t) {
- vector<int> v;
- for (int i = 0; i <= s.size() - t.size(); ++ i)
- if (s[i] == t[0])
- v.push_back(i);
- for (int i = 0; i < v.size(); ++ i) {
- int j = t.size() - 1;
- for (; j >= 0; -- j) {
- if (s[v[i] + j] != t[j]) break;
- }
- if (j == -1) return v[i];
- }
- return -1;
- }
- int main() {
- string s, t;
- cin >> s >> t;
- cout << BM(s, t) << endl;
- cout << RB(s, t) << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement