Advertisement
Mlxa

### Матрицы с оптимизированным умножением

Feb 13th, 2019
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.69 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. using ll = long long;
  4. #define long ll
  5. #define all(x) begin(x), end(x)
  6.  
  7. using Scalar = long;
  8.  
  9. struct Matrix {
  10.     int n, m;
  11.     vector<Scalar> data;
  12.    
  13.     Matrix() : n(0), m(0), data(0) {}
  14.    
  15.     Matrix(int x, int y) :
  16.         n(x),
  17.         m(y),
  18.         data(x * y, 0) {}
  19.    
  20.     Scalar &operator()(int i, int j) {
  21.         //assert(0 <= i && i < n);
  22.         //assert(0 <= j && j < m);
  23.         return data[i * n + j];
  24.     }
  25.    
  26.     Scalar operator()(int i, int j) const {
  27.         //assert(0 <= i && i < n);
  28.         //assert(0 <= j && j < m);
  29.         return data[i * n + j];
  30.     }
  31. };
  32.  
  33. Matrix identity(int n) {
  34.     Matrix a(n, n);
  35.     for (int i = 0; i < n; ++i) {
  36.         a(i, i) = 1;
  37.     }
  38.     return a;
  39. }
  40.  
  41. Matrix transpose(const Matrix &a) {
  42.     int n = a.n, m = a.m;
  43.     Matrix b(m, n);
  44.     for (int i = 0; i < n; ++i) {
  45.         for (int j = 0; j < m; ++j) {
  46.             b(i, j) = a(j, i);
  47.         }
  48.     }
  49.     return b;
  50. }
  51.  
  52. Matrix operator*(const Matrix &a, Matrix b) {
  53.     assert(a.m == b.n);
  54.     int n = a.n, m = b.m, k = a.m;
  55.     b = transpose(b);
  56.     Matrix c(n, m);
  57.     for (int i = 0; i < n; ++i) {
  58.         for (int j = 0; j < m; ++j) {
  59.             for (int t = 0; t < k; ++t) {
  60.                 c(i, j) += a(i, t) * b(j, t);
  61.             }
  62.         }
  63.     }
  64.     return c;
  65. }
  66.  
  67. Matrix fast_power(Matrix a, int p) {
  68.     assert(a.n == a.m);
  69.     int n = a.n;
  70.     Matrix x = identity(n);
  71.     for (; p > 0; p >>= 1) {
  72.         if (p & 1) {
  73.             x = x * a;
  74.         }
  75.         a = a * a;
  76.     }
  77.     return x;
  78. }
  79.  
  80. ostream &operator<<(ostream &out, const Matrix &a) {
  81.     for (int i = 0; i < a.n; ++i) {
  82.         for (int j = 0; j < a.m; ++j) {
  83.             out << a(i, j) << '\t';
  84.         }
  85.         out << '\n';
  86.     }
  87.     return out;
  88. }
  89.  
  90.  
  91. int main() {
  92. #ifdef LC
  93.     //assert(freopen("input.txt", "r", stdin));
  94. #endif
  95.     ios::sync_with_stdio(false);
  96.     cin.tie(nullptr);
  97.  
  98.     return 0;
  99. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement