Manioc

hashu

Jun 22nd, 2018
201
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.03 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define MAX 100007
  3.  
  4. using namespace std;
  5.  
  6. typedef long long ll;
  7.  
  8. ll h[4*MAX], power[MAX], inv[MAX];
  9. ll base[2] = {317, 307};
  10. ll mod[2] = {104000717, 104000711};
  11. int n;
  12.  
  13. ll gcd(ll a, ll m){
  14.     ll x = 1, y = 0, ini = m;
  15.     if(m == 1) return 0;
  16.  
  17.     while(a > 1){
  18.         ll q = a/m;
  19.  
  20.         ll t = m;
  21.         m = a%m;
  22.         a = t;
  23.         t = y;
  24.         y = x-q*y;
  25.         x = t;
  26.     }
  27.  
  28.     if(x < 0) x += ini;
  29.     return x;
  30. }
  31.  
  32. void init(){
  33.     power[0] = base[0];
  34.     inv[0] = gcd(base[0], mod[0]);
  35.     cout << inv[0] << endl;
  36.     for(int i = 1; i < MAX; i++){
  37.         power[i] = (power[i-1]*base[0])%mod[0];
  38.         inv[i] = (inv[i-1]*inv[0])%mod[0];
  39.     }
  40. }
  41.  
  42. void update(int idx, char now, char old = '$'){
  43.     cout << now << " " << old << endl;
  44.     int pos = idx;
  45.     if(old == '$') for(; idx <= n; idx += idx&(-idx)) h[idx] = (h[idx] + (now-'a'+1)*power[pos])%mod[0];
  46.     else{
  47.         for(; idx <= n; idx += idx&(-idx)) {
  48.             h[idx] = (h[idx] - (old-'a'+1)*power[pos])%mod[0];
  49.             while(h[idx] < 0) h[idx] += mod[0];
  50.             h[idx] = (h[idx] + (now-'a'+1)*power[pos])%mod[0];
  51.             while(h[idx] < 0) h[idx] += mod[0];
  52.         }
  53.     }
  54. }
  55. void getHash(string s){
  56.     for(int i = 1; i <= s.size(); i++) update(i, s[i-1]);
  57. }
  58.  
  59. ll query(int idx){
  60.     ll hash = 0;
  61.     for(; idx > 0; idx -= idx&(-idx)) hash = (hash + h[idx])%mod[0];
  62.     return hash;
  63. }
  64.  
  65. ll query(int l, int r){
  66.     return (((query(r)-query(l-1)+ mod[0])%mod[0])*inv[l])%mod[0];
  67. }
  68. int main(){
  69.     string txt; cin >> txt;
  70.     n = txt.size();
  71.     init();
  72.     //cout << "ola\n";
  73.     getHash(txt);
  74.     //cout << "oi\n";
  75.     int k; cin >> k;
  76.     while(k--){
  77.         int tipo; cin >> tipo;
  78.         if(!tipo){
  79.             int l, r; cin >> l >> r;
  80.             cout << query(l, r) << endl;
  81.         }else{
  82.             int idx;
  83.             char letra; cin >> idx >> letra;
  84.             update(idx, letra, txt[idx-1]);
  85.             txt[idx-1] = letra;
  86.         }
  87.     }
  88.     return 0;
  89. }
Advertisement
Add Comment
Please, Sign In to add comment