C++ container for matrices.
1/* ========================================================================
2 *
3 * Filename: main.cpp
4 * Description: matrix algorithms
5 * Author: Diego A. Estrada Rivera
6 * Version: 0.0.1
7 *
8 * ======================================================================== */
9
10#include <iostream>
11auto println(auto x)
12{
13 std::cout << x << std::endl;
14}
15auto print(auto x)
16{
17 std::cout << x;
18}
19
20#include <bits/stdc++.h>
21using namespace std;
22typedef size_t sz;
23typedef uint64_t u64;
24typedef vector<u64> vi;
25typedef pair<u64, u64> ii;
26typedef vector<pair<u64, u64>> vii;
27typedef vector<vector<u64>> vvi;
28
29struct Matrix {
30 Matrix(sz r, sz c) : data(vi(r * c, 0)), cols(c), rows(r)
31 {
32 }
33
34 u64& operator[](sz i)
35 {
36 return data[i];
37 }
38
39 u64& operator()(sz r, sz c)
40 {
41 return data[r * cols + c];
42 }
43
44 u64 operator()(sz r, sz c) const
45 {
46 return data[r * cols + c];
47 }
48
49 vi get_row(sz r) const
50 {
51 auto ret = vi(cols, 0);
52 sz i = 0;
53 for (auto& e : ret) {
54 e = data[rows * r + i];
55 i++;
56 }
57 return ret;
58 }
59
60 vi get_col(sz c) const
61 {
62 auto ret = vi(rows, 0);
63 sz i = 0;
64 for (auto& e : ret) {
65 e = data[cols * i + c];
66 i++;
67 }
68 return ret;
69 }
70
71 void print() const
72 {
73 for (sz i = 0; i < rows; i++) {
74 for (sz j = 0; j < cols; j++)
75 cout << (*this)(i, j) << " ";
76 cout << endl;
77 }
78 }
79
80 Matrix operator*(const Matrix& rhs) const
81 {
82 auto out = Matrix(rhs.rows, cols);
83 for (sz i = 0; i < cols; i++) {
84 auto sel_row = get_row(i);
85 for (sz j = 0; j < rhs.rows; j++) {
86 auto sel_col = rhs.get_col(j);
87 u64 sum = inner_product(sel_row.begin(),
88 sel_row.end(),
89 sel_col.begin(), 0);
90 out(i, j) = sum;
91 }
92 }
93 return out;
94 }
95
96 void operator*=(const Matrix& rhs)
97 {
98 for (sz i = 0; i < cols; i++) {
99 auto sel_row = get_row(i);
100 for (sz j = 0; j < rhs.rows; j++) {
101 auto sel_col = rhs.get_col(j);
102 u64 sum = inner_product(sel_row.begin(),
103 sel_row.end(),
104 sel_col.begin(), 0);
105 (*this)(i, j) = sum;
106 }
107 }
108 }
109
110 vi data;
111 sz cols;
112 sz rows;
113};
114
115auto main() -> int
116{
117 auto m = Matrix(2, 2);
118 m(0, 0) = 1;
119 m(0, 1) = 1;
120 m(1, 0) = 1;
121 auto l = Matrix(2, 1);
122 l(0, 0) = 0;
123 l(1, 0) = 1;
124 m.print();
125 cout << endl;
126 auto n = 0lu;
127 cin >> n;
128 while ((n /= 2) <= 1)
129 m = m * m;
130 if (!(n & 1))
131 m = m * m;
132
133 m.print();
134
135 return 0;
136}