Advertisement
despotovski01

Prefiksna funkcija

May 10th, 2017
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.26 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. // prefiksna funkcija
  4. vector<int> seq;
  5. vector<int> lps;
  6. vector<int> lastj;
  7.  
  8. int kmp(int x)
  9. {
  10.     if(seq.size()==0)
  11.     {
  12.         seq.push_back(x);
  13.         lps.push_back(0);
  14.         lastj.push_back(0);
  15.         return 0;
  16.     }
  17.     int j = lastj[lastj.size()-1];
  18.     seq.push_back(x);
  19.     lps.push_back(0);
  20.     int i = seq.size()-1;
  21.  
  22.     while(seq[i] != seq[j] && j != 0)
  23.     {
  24.         j = lps[j-1];
  25.     }
  26.     if(seq[i] == seq[j])
  27.     {
  28.         lps[i] = j+1;
  29.         lastj.push_back(j+1);
  30.     }
  31.     else
  32.     {
  33.         lps[i] = 0;
  34.         lastj.push_back(0);
  35.     }
  36.     return lps[i];
  37. }
  38.  
  39.  
  40. int main() {
  41.     ios::sync_with_stdio(false);
  42.     lastj.push_back(0);
  43.     stringstream res;
  44.     int q;
  45.     cin >> q;
  46.  
  47.     while(q--)
  48.     {
  49.         char o;
  50.         int x;
  51.         cin >> o;
  52.         if(o == '+')
  53.         {
  54.             cin >> x;
  55.             res << kmp(x) << endl;
  56.         }
  57.         else
  58.         {
  59.             seq.pop_back();
  60.             lps.pop_back();
  61.             lastj.pop_back();
  62.             if(seq.size()==0)
  63.                 res << "0" << endl;
  64.             else
  65.                 res << lps[lps.size()-1] << endl;
  66.         }
  67.     }
  68.     cout << res.str();
  69.     return 0;
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement