File tree 1 file changed +81
-0
lines changed 1 file changed +81
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include < iostream>
2
+ #include < vector>
3
+
4
+ #include < gmpxx.h>
5
+
6
+ template <typename T>
7
+ void divide_row (std::vector<T> &A, T ratio) {
8
+ for (auto & num : A) {
9
+ num /= ratio;
10
+ }
11
+ }
12
+
13
+ template <typename T>
14
+ void equalize_row (std::vector<T> const & A, std::vector<T> &B, T ratio) {
15
+ int32_t n = A.size ();
16
+ for (int32_t i = 0 ; i < n; i++) {
17
+ B[i] += A[i]*ratio;
18
+ }
19
+ }
20
+
21
+ template <typename T>
22
+ void print_matrix (std::vector<std::vector<T>> const & A) {
23
+ for (auto const & row : A) {
24
+ for (auto const & num : row) {
25
+ std::cout << num << " " ;
26
+ }
27
+ std::cout << " \n " ;
28
+ }
29
+ }
30
+
31
+ template <typename T>
32
+ T determinant (std::vector<std::vector<T>> A) {
33
+ T ans = 1 ;
34
+
35
+ int32_t n = A.size ();
36
+ for (int32_t i = 0 ; i < n; i++) {
37
+ int32_t best = i;
38
+
39
+ for (int32_t j = i+1 ; j < n; j++) {
40
+ if (abs (A[best][i]) < abs (A[j][i])) {
41
+ best = j;
42
+ }
43
+ }
44
+
45
+ if (best != i) {
46
+ ans = -ans;
47
+ std::swap (A[best], A[i]);
48
+ }
49
+
50
+ ans *= T (A[i][i]);
51
+ divide_row<T>(A[i], A[i][i]);
52
+
53
+ for (int32_t j = i+1 ; j < n; j++) {
54
+ equalize_row<T>(A[i], A[j], -A[j][i]);
55
+ }
56
+ }
57
+
58
+ for (int32_t i = 0 ; i < n; i++) {
59
+ ans *= A[i][i];
60
+ }
61
+
62
+ return ans;
63
+ }
64
+
65
+ int main () {
66
+ using rational = mpq_class;
67
+
68
+ int32_t n;
69
+ std::cin >> n;
70
+
71
+ auto M = std::vector<std::vector<rational>>(n, std::vector<rational>(n));
72
+ for (auto & row : M) {
73
+ for (auto & x : row) {
74
+ std::cin >> x;
75
+ }
76
+ }
77
+
78
+ auto x = determinant<rational>(M);
79
+
80
+ std::cout << x << " \n " ;
81
+ }
You can’t perform that action at this time.
0 commit comments