Advertisement
STANAANDREY

tpa pb propusa tema o(logn)

May 4th, 2023 (edited)
969
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.31 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. const string FNAME = "data";
  4. ifstream fin(FNAME + ".in");
  5. ofstream fout(FNAME + ".out");
  6. using Matrix2x2 = array<array<int, 2>, 2>;
  7. constexpr int MOD = 1'000'000'007;//'
  8. constexpr Matrix2x2 IDENTITY{{ {1, 0}, {0, 1} }};
  9.  
  10. Matrix2x2 multiplyMatrices(const Matrix2x2 a, const Matrix2x2 b) {
  11.     Matrix2x2 res;
  12.     for (int i = 0; i < 2; i++) {
  13.         for (int j = 0; j < 2; j++) {
  14.             int sum = 0;
  15.             for (int k = 0; k < 2; k++) {
  16.                 sum = (sum + 1LL * a[i][k] * b[k][j] % MOD) % MOD;
  17.             }
  18.             res[i][j] = sum;
  19.         }
  20.     }
  21.     return res;
  22. }
  23.  
  24. Matrix2x2 toLogPowMatrix(Matrix2x2 base, int exp) {
  25.     Matrix2x2 res = IDENTITY;
  26.     while (exp) {
  27.         if (exp & 1) {
  28.             res = multiplyMatrices(res, base);
  29.         }
  30.         base = multiplyMatrices(base, base);
  31.         exp >>= 1;
  32.     }
  33.     return res;
  34. }
  35.  
  36. int main() {
  37.     constexpr Matrix2x2 iniStateMatrix{{ {1, 3}, {0, 0} }};
  38.     constexpr Matrix2x2 transMatrix{{ {0, 2}, {1, 1} }};
  39.     int n;
  40.     fin >> n;
  41.     assert(3 <= n && n <= 1e9);
  42.     Matrix2x2 poweredMatrix = toLogPowMatrix(transMatrix, n - 2);
  43.     Matrix2x2 res = multiplyMatrices(iniStateMatrix, poweredMatrix);
  44.     fout << res[0][1] << endl;
  45.     fout.close();
  46.     return 0;
  47. }
  48.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement