Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <queue>
- using namespace std;
- typedef long long ll;
- typedef vector<vector<int>> matrix;
- const int maxn = 1e5 + 10;
- const int INF = 2e9;
- matrix multiply_by_k(matrix A, int k) {
- matrix res = A;
- int n = (int) A.size(), m = (int) A[0].size();
- for(int i = 0; i < n; i++) {
- for(int j = 0; j < m; j++) {
- res[i][j] *= k;
- }
- }
- return res;
- }
- matrix add_two_matrices(matrix A, matrix B) {
- int n_a = (int) A.size(), m_a = (int) A[0].size();
- int n_b = (int) B.size(), m_b = (int) B[0].size();
- if(n_a == n_b and m_a == m_b) {
- matrix res = A;
- for(int i = 0; i < n_a; i++) {
- for(int j = 0; j < m_a; j++) {
- res[i][j] = A[i][j] + B[i][j];
- }
- }
- return res;
- }
- cout << "Dimenziite na matricite treba da se isti za da mozhe da gi sobereme istite" << endl;
- return {{0}};
- }
- matrix subtract_two_matrices(matrix A, matrix B) {
- int n_a = (int) A.size(), m_a = (int) A[0].size();
- int n_b = (int) B.size(), m_b = (int) B[0].size();
- if(n_a != n_b or m_a != m_b) {
- cout << "Dimenziite na matricite treba da se isti za da mozhe da gi sobereme istite" << endl;
- return {{0}};
- }
- matrix res = A;
- for(int i = 0; i < n_a; i++) {
- for(int j = 0; j < m_a; j++) {
- res[i][j] = A[i][j] - B[i][j];
- }
- }
- return res;
- }
- matrix multiply_two_matrices(matrix A, matrix B) {
- int n_a = (int) A.size(), m_a = (int) A[0].size();
- int n_b = (int) B.size(), m_b = (int) B[0].size();
- if(m_a != n_b) {
- cout << "Matricite ne mozhat da se mnozhat" << endl;
- return {{0}};
- }
- matrix res(n_a, vector<int>(m_b, 0));
- for(int i = 0; i < n_a; i++) {
- for(int j = 0; j < m_b; j++) {
- int c = 0;
- for(int k = 0; k < n_a; k++) {
- c += A[i][k] * B[k][j];
- }
- res[i][j] = c;
- }
- }
- return res;
- }
- void print(matrix A) {
- int n = (int) A.size(), m = (int) A[0].size();
- for(int i = 0; i < n; i++) {
- for(int j = 0; j < m; j++) {
- cout << A[i][j] << " ";
- }
- cout << endl;
- }
- cout << endl;
- }
- int main() {
- matrix A = {
- {1, 2},
- {3, 4}
- };
- matrix B = {
- {1, 2, 3},
- {4, 5, 6},
- };
- matrix multiplied_by_k = multiply_by_k(A, 2);
- print(multiplied_by_k);
- matrix add_two_matrix = add_two_matrices(A, B);
- print(add_two_matrix);
- matrix subtrac_two_matrix = subtract_two_matrices(A, B);
- print(subtrac_two_matrix);
- matrix multiplication_two_matrices = multiply_two_matrices(A, B);
- print(multiplication_two_matrices);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement