fork download
  1.  
  2. /*
  3.   Copyright 2011 Marek "p2004a" Rusinowski
  4.   Matrix multiplication (class matrix)
  5. */
  6. #include <cstdio>
  7. #include <cstring>
  8. #include <cassert>
  9.  
  10. class Matrix {
  11. private:
  12. static const int cmod = 1000000007;
  13. int n_;
  14. int *t_;
  15.  
  16. public:
  17. Matrix(int n) : n_(n), t_(new int [n_ * n_]) {}
  18.  
  19. Matrix(int n, const int *t) : n_(n), t_(new int [n_ * n_]) {
  20. memcpy(t_, t, sizeof(int) * n_ * n_);
  21. }
  22.  
  23. Matrix(const Matrix &obj) : n_(obj.n_), t_(new int [n_ * n_]) {
  24. memcpy(t_, obj.t_, sizeof(int) * n_ * n_);
  25. }
  26.  
  27. ~Matrix() {
  28. delete t_;
  29. }
  30.  
  31. Matrix &operator=(const Matrix &obj) {
  32. if (&obj == this) {
  33. return *this;
  34. }
  35. if (obj.n_ != n_) {
  36. delete t_;
  37. n_ = obj.n_;
  38. t_ = new int [n_ * n_];
  39. }
  40. memcpy(t_, obj.t_, sizeof(int) * n_ * n_);
  41. return *this;
  42. }
  43.  
  44. const Matrix operator*(const Matrix &obj) {
  45. assert(obj.n_ == n_);
  46. Matrix res(n_);
  47. for (int i = 0; i < n_; ++i) {
  48. for (int k = 0; k < n_; ++k) {
  49. for (int j = 0; j < n_; ++j) {
  50. *(res.t_ + n_ * i + j) += *(t_ + n_ * i + k) * *(obj.t_ + n_ * k + j) % cmod;
  51. *(res.t_ + n_ * i + j) %= cmod;
  52. }
  53. }
  54. }
  55. return res;
  56. }
  57.  
  58. Matrix &operator*=(const Matrix &obj) {
  59. (*this) = (*this) * obj;
  60. return *this;
  61. }
  62.  
  63. const int *operator[](int i) {
  64. return t_ + n_ * i;
  65. }
  66. };
  67.  
  68. void read_matrix(int n, int *t) {
  69. for (int i = 0; i < n; ++i) {
  70. for (int j = 0; j < n; ++j) {
  71. scanf("%d", t + n * i + j);
  72. }
  73. }
  74. }
  75.  
  76. int main() {
  77. int n;
  78. scanf("%d", &n);
  79. int *a = new int [n * n], *b = new int [n * n];
  80. read_matrix(n, a);
  81. read_matrix(n, b);
  82. Matrix A(n, a), B(n, b);
  83. A *= B;
  84. for (int i = 0; i < n; ++i) {
  85. for (int j = 0; j < n; ++j) {
  86. printf("%3d ", A[i][j]);
  87. }
  88. printf("\n");
  89. }
  90. delete a;
  91. delete b;
  92. return 0;
  93. }
  94.  
stdin
2

2 1 
1 1

2 1
1 1
compilation info
prog.cpp: In function ‘void read_matrix(int, int*)’:
prog.cpp:71: warning: ignoring return value of ‘int scanf(const char*, ...)’, declared with attribute warn_unused_result
prog.cpp: In function ‘int main()’:
prog.cpp:78: warning: ignoring return value of ‘int scanf(const char*, ...)’, declared with attribute warn_unused_result
stdout
  5   3 
  3   2