Advertisement
Yesver08

b.cpp

Apr 27th, 2024
571
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.37 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. using namespace std;
  5. #define ull long long
  6.  
  7. typedef vector<vector<ull>> Matrix;
  8. const ull MOD = 1000000007;
  9.  
  10. Matrix multiply(const Matrix& A, const Matrix& B) {
  11.     ull n = A.size();
  12.     Matrix result(n, vector<ull>(n, 0));
  13.     for (ull i = 0; i < n; ++i) {
  14.         for (ull j = 0; j < n; ++j) {
  15.             for (ull k = 0; k < n; ++k) {
  16.                 result[i][j] =
  17.                     (result[i][j] + (ull)A[i][k] * B[k][j] % MOD) % MOD;
  18.             }
  19.         }
  20.     }
  21.     return result;
  22. }
  23.  
  24. Matrix matrixPower(Matrix M, ull exp) {
  25.     ull n = M.size();
  26.     Matrix result(n, vector<ull>(n, 0));
  27.     for (ull i = 0; i < n; ++i) {
  28.         result[i][i] = 1;
  29.     }
  30.  
  31.     while (exp > 0) {
  32.         if (exp % 2 == 1) {
  33.             result = multiply(result, M);
  34.         }
  35.         M = multiply(M, M);
  36.         exp /= 2;
  37.     }
  38.     return result;
  39. }
  40.  
  41. ull matrixExponentiation(ull N) {
  42.     Matrix M = {{0, 2, 1, 0}, {1, 0, 0, 1}, {1, 0, 0, 0}, {0, 1, 0, 0}};
  43.     vector<ull> V2 = {0, 1, 1, 0};
  44.  
  45.     if (N == 1) {
  46.         return V2[0];
  47.     }
  48.  
  49.     Matrix M_power = matrixPower(M, N - 1);
  50.     ull result = 0;
  51.     for (ull i = 0; i < 4; ++i) {
  52.         result = (result + (ull)M_power[0][i] * V2[i] % MOD) % MOD;
  53.     }
  54.  
  55.     return result;
  56. }
  57.  
  58. int main() {
  59.     ull N;
  60.     cin >> N;
  61.     cout << matrixExponentiation(N);
  62. }
  63.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement