Advertisement
Guest User

d.cpp

a guest
Dec 12th, 2019
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.91 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. const int mod = (int)1e9+7;
  3. int pow(int a, int n) {
  4.     int res = 1;
  5.     while (n > 0) {
  6.         if (n % 2 == 1) {
  7.             res = int(1LL * res * a % mod);
  8.         }
  9.         a = int(1LL * a * a % mod);
  10.         n /= 2;
  11.     }
  12.     return res;
  13. }
  14. int main() {
  15.     std::ios_base::sync_with_stdio(false);
  16.     std::cin.tie(0);
  17.     // input:
  18.     int n;
  19.     std::cin >> n;
  20.     std::string s;
  21.     std::cin >> s;
  22.     // counting letters:
  23.     std::vector<int> count(256);
  24.     for (int i = 0; i < n; i++) {
  25.         count[s[i]]++;
  26.     }
  27.     // calculating factorials:
  28.     std::vector<int> factorial(1+n);
  29.     factorial[0] = 1;
  30.     for (int i = 1; i <= n; i++) {
  31.         factorial[i] = int(1LL * factorial[i-1] * i % mod);
  32.     }
  33.     // calculating inverse factorials in linear time:
  34.     // 1/n! = pow(n!, mod-2)
  35.     std::vector<int> inverseFactorial(1+n);
  36.     inverseFactorial[n] = pow(factorial[n], mod-2);
  37.     // 1/(n-1)! = n * (1/n!)
  38.     for (int i = n-1; i >= 0; i--) {
  39.         inverseFactorial[i] = int(1LL * inverseFactorial[i+1] * (i+1) % mod);
  40.     }
  41.     // getting answer:
  42.     int answ = factorial[n];
  43.     for (char c = 'a'; c <= 'z'; c++) {
  44.         answ = int(1LL * answ * inverseFactorial[count[(int)c]] % mod);
  45.     }
  46.     std::cout << answ << std::endl;
  47.     // answering on queries:
  48.     int q; std::cin >> q;
  49.     while (q--) {
  50.         int pos; char newChar;
  51.         std::cin >> pos >> newChar;
  52.         pos--;
  53.         char oldChar = s[pos];
  54.         s[pos] = newChar;
  55.         answ = int(1LL * answ * factorial[count[(int)oldChar]] % mod);
  56.         answ = int(1LL * answ * factorial[count[(int)newChar]] % mod);
  57.         count[oldChar]--;
  58.         count[newChar]++;
  59.         answ = int(1LL * answ * inverseFactorial[count[(int)oldChar]] % mod);
  60.         answ = int(1LL * answ * inverseFactorial[count[(int)newChar]] % mod);
  61.         std::cout << answ << "\n";
  62.     }
  63.     return 0;
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement