include iostream include vector include iomanip include cmath using na

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include <iostream>
#include <vector>
#include <iomanip>
#include <cmath>
using namespace std;
vector <double> matrix_mult(vector <vector <double> > &matrix, vector <double> a) {
vector <double> before = a;
for (int i = 0; i < a.size(); ++i) {
double cur = 0.0;
for (int j = 0; j < a.size(); ++j) {
cur += matrix[i][j] * before[j];
}
a[i] = cur;
}
return a;
}
vector <double> matrix_subtruct(vector <double> a, vector <double> &b) {
for (int i = 0; i < a.size(); ++i) {
a[i] -= b[i];
}
return a;
}
vector <double> matrix_add(vector <double> a, vector <double> &b) {
for (int i = 0; i < a.size(); ++i) {
a[i] += b[i];
}
return a;
}
double dot_product(vector <double> &a, vector <double> &b) {
double ret = 0.0;
for (int i = 0; i < a.size(); ++i) {
ret += a[i] * b[i];
}
return ret;
}
vector <double> matrix_mult_const(vector <double> a, double c) {
for (int i = 0; i < a.size(); ++i) {
a[i] *= c;
}
return a;
}
int main() {
freopen("input.txt", "r", stdin);
int n;
cin >>n;
vector <vector <double> > matrix (n, vector <double> (n));
vector <double> b(n);
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
cin >>matrix[i][j];
}
cin >>b[i];
}
double eps;
cin >>eps;
double INF = 1e5 * 1.0;
vector <double> xi(n), p(n), q(n), x(n, 0.0);
double alpha, betta;
xi = matrix_subtruct(b, matrix_mult(matrix, x));
p = xi;
while (sqrt(dot_product(xi, xi)) / sqrt(dot_product(b, b)) > eps) {
q = matrix_mult(matrix, p);
alpha = dot_product(xi, p) / dot_product(q, p);
x = matrix_add(x, matrix_mult_const(p, alpha));
xi = matrix_subtruct(xi, matrix_mult_const(q, alpha));
betta = dot_product(xi, q) / dot_product(q, p);
p = matrix_subtruct(xi, matrix_mult_const(p, betta));
q = matrix_mult(matrix, p);
}
cout <<fixed <<setprecision(5);
for (int i = 0; i < n; ++i) {
cout <<"X" <<i + 1 <<" = " <<x[i] <<endl;
}
return 0;
}