Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- using ld = long double;
- const ld EPS = 1e-10;
- struct Vector {
- vector<ld> v;
- int n;
- Vector() {
- cout << "Zero vector\n";
- }
- Vector(int n) : n(n), v(n) {};
- Vector(const vector<ld>& o) : v(o), n(o.size()) {}
- Vector operator + (Vector o) {
- Vector ans = v;
- if (ans.v.size() != o.v.size()) throw;
- for (int i = 0; i < v.size(); i++) {
- ans.v[i] += o[i];
- }
- return ans;
- }
- Vector operator - (Vector o) {
- Vector ans = v;
- if (ans.v.size() != o.v.size()) throw;
- for (int i = 0; i < v.size(); i++) {
- ans[i] -= o.v[i];
- }
- return ans;
- }
- ld operator * (Vector o) {
- ld ans = 0;
- for (int i = 0; i < v.size(); i++) {
- ans += v[i] * o.v[i];
- }
- return ans;
- }
- Vector operator * (const ld d) {
- Vector ans = v;
- for (int i = 0; i < n; i++) {
- ans[i] *= d;
- }
- return ans;
- }
- Vector operator / (const ld d) {
- if (abs(d) < EPS) throw;
- Vector ans = v;
- for (int i = 0; i < v.size(); i++) {
- ans[i] /= d;
- }
- return ans;
- }
- ld& operator [] (const int i) {
- return v[i];
- }
- };
- struct Matrix {
- vector<Vector> t;
- int n;
- Matrix(int n) : n(n) {
- for (int i = 0; i < n; i++) {
- t.emplace_back(n);
- }
- }
- Matrix (const vector<Vector>& o) : t(o) {
- n = o.size();
- }
- void Transponse() {
- for (int i = 0; i < n; i++) {
- for (int j = 0; j < i; j++) {
- swap(t[i][j], t[j][i]);
- }
- }
- }
- Vector& operator [] (const int i) {
- return t[i];
- }
- Matrix operator * (Matrix& o) {
- assert(n == o.n);
- Matrix ans(n);
- for (int i = 0; i < n; i++) {
- for (int j = 0; j < n; j++) {
- for (int k = 0; k < n; k++) {
- ans[i][k] += t[i][j] * o[j][k];
- }
- }
- }
- return ans;
- }
- Matrix inv() {
- Matrix ans(n);
- for (int i = 0; i < n; i++) {
- ans[i][i] = 1;
- }
- Matrix cur(t);
- for (int i = 0; i < n; i++) {
- int nxt = -1;
- for (int j = i; j < n; j++) {
- if (abs(cur[i][j]) > EPS) {
- nxt = j;
- break;
- }
- }
- if (nxt == -1) throw;
- if (nxt != i) {
- cur[i] = cur[i] + cur[nxt];
- ans[i] = ans[i] + ans[nxt];
- }
- ans[i] = ans[i] / cur[i][i];
- cur[i] = cur[i] / cur[i][i];
- for (int j = 0; j < n; j++) {
- if (i == j) continue;
- ans[j] = ans[j] - ans[i] * cur[j][i];
- cur[j] = cur[j] - cur[i] * cur[j][i];
- }
- }
- return ans;
- };
- void Print() {
- for (int i = 0; i < n; i++) {
- for (int j = 0; j < n; j++) {
- cout << fixed << setprecision(15) << t[i][j] << " ";
- }
- cout << "\n";
- }
- cout << "\n";
- }
- };
- int main() {
- const int n = 5;
- Matrix a(n);
- for (int i = 0; i < n; i++) {
- for (int j = 0; j < n; j++) {
- a[i][j] = rand() % 300;
- }
- }
- a.Print();
- auto a_inv = a.inv();
- a_inv.Print();
- auto e = a * a_inv;
- e.Print();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement