StoneHaos

3

Jan 26th, 2022 (edited)
334
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.71 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3.  
  4. using namespace std;
  5. typedef unsigned long long uii;
  6.  
  7. const int MOD = 65537;
  8.  
  9. int Brute(string p, string t) {
  10.     int n = t.size();
  11.     int m = p.size();
  12.     int b = 0;
  13.     int x = -1;
  14.     for (int i = 0; i <= n - m; ++ i) {
  15.         for (b = 0; b < m && p[b] == t[i + b]; ++ b);
  16.         if (b == m) {
  17.             x = i;
  18.             break;
  19.         }
  20.     }
  21.     return x;
  22. }
  23.  
  24. int pm(int a, int b, int c) {
  25.     if (b == 0) return 1;
  26.     if (b % 2 == 1) return (int)(((uii)a * (uii)pm(a, b - 1, c)) % (uii)c);
  27.     else {
  28.         uii x = (uii)pm(a, b / 2, c);
  29.         return (int)((x * x) % (uii)c);
  30.     }
  31. }
  32.  
  33. int f(string s, int a, int b, int q) {
  34.     int x = 2;
  35.     int res = 0;
  36.     int n = b - a;
  37.     for (int i = 0; i < n; ++ i) {
  38.         res = ((res % q) + ((s[a + i] % q) * ((pm(x, n - i - 1, q) % q)) % q)) % q;
  39.     }
  40.     return res;
  41.  
  42. }
  43.  
  44. int g(string s, int oldhash, int oldc, int newc, int q) {
  45.     int x = 2;
  46.     int step = newc - oldc - 1;
  47.     int newhash = oldhash;
  48.     int d1 = ((s[oldc] % q) * pm(x, step, q)) % q;
  49.     while (newhash < d1) newhash += q;
  50.     newhash = (newhash - d1) % q;
  51.     newhash = (newhash * (x % q)) % q;
  52.     newhash = (newhash + (s[newc] % q)) % q;
  53.     return newhash;
  54. }
  55.  
  56. int RK(string p, string t) {
  57.     int n = t.size();
  58.     int m = p.size();
  59.     int hashp = f(p, 0, m, MOD);
  60.     int hasht = f(t, 0, m, MOD);
  61.     for (int i = 0; i <= n - m; ++ i) {
  62.         if (hasht == hashp) {
  63.             int j = 0;
  64.             for (; j < m && p[j] == t[i + j]; ++ j);
  65.             if (j == m)
  66.                 return i;
  67.         }
  68.         if (i < n - m)
  69.             hasht = g(t, hasht, i, i + m, MOD);
  70.     }
  71.     return -1;
  72. }
  73.  
  74. int main(void) {
  75.     string t, p;
  76.     cout << "Input string>";
  77.     cin >> t;
  78.     cout << "Input sample>";
  79.     cin >> p;
  80.     int res1 = Brute(p, t);
  81.     int res2 = RK(p, t);
  82.     cout << res1 << endl << res2 << endl;
  83.     return 0;
  84. }
Add Comment
Please, Sign In to add comment