Skip to content

Commit b925fb8

Browse files
committed
Compute det in inv
1 parent 1604673 commit b925fb8

File tree

4 files changed

+17
-16
lines changed

4 files changed

+17
-16
lines changed

cp-algo/linalg/matrix.hpp

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -182,16 +182,18 @@ namespace cp_algo::linalg {
182182
return res;
183183
}
184184

185-
std::optional<matrix> inv() const {
185+
std::pair<base, matrix> inv() const {
186186
assert(n() == m());
187187
matrix b = *this | eye(n());
188188
if(size(b.echelonize<reverse>(n())[0]) < n()) {
189-
return std::nullopt;
189+
return {0, {}};
190190
}
191+
base det = 1;
191192
for(size_t i = 0; i < n(); i++) {
193+
det *= b[i][i];
192194
b[i] *= base(1) / b[i][i];
193195
}
194-
return b.submatrix(std::slice(0, n(), 1), std::slice(n(), n(), 1));
196+
return {det, b.submatrix(std::slice(0, n(), 1), std::slice(n(), n(), 1))};
195197
}
196198

197199
// Can also just run gauss on T() | eye(m)

verify/linalg/adj.test.cpp

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,12 +24,11 @@ void solve() {
2424
A[i][n] = cp_algo::random::rng();
2525
A[n][i] = cp_algo::random::rng();
2626
}
27-
auto Ai = A.inv();
28-
auto D = A.det();
27+
auto [D, Ai] = A.inv();
2928
for(int i: views::iota(0, n)) {
3029
for(int j: views::iota(0, n)) {
3130
if(D != 0) {
32-
auto res = (*Ai)[n][n] * (*Ai)[i][j] - (*Ai)[i][n] * (*Ai)[n][j];
31+
auto res = Ai[n][n] * Ai[i][j] - Ai[i][n] * Ai[n][j];
3332
cout << res * D << " \n"[j + 1 == n];
3433
} else {
3534
cout << 0 << " \n"[j + 1 == n];

verify/linalg/inv.test.cpp

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,11 +15,11 @@ void solve() {
1515
cin >> n;
1616
matrix<modint<mod>> a(n, n);
1717
a.read();
18-
auto ai = a.inv();
19-
if(!ai) {
18+
auto [d, ai] = a.inv();
19+
if(d == 0) {
2020
cout << -1 << "\n";
2121
} else {
22-
ai->print();
22+
ai.print();
2323
}
2424
}
2525

verify/linalg/tutte.test.cpp

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -32,17 +32,17 @@ void solve() {
3232
B[i][j] = T[pivots[i]][pivots[j]];
3333
}
3434
}
35-
B = *B.inv();
35+
auto [d, Bi] = B.inv();
3636
vector<pair<int, int>> ans;
3737
for(size_t i = 0; i < size(pivots); i++) {
3838
for(size_t j = 0; j < size(pivots); j++) {
39-
if(T[pivots[i]][pivots[j]] != 0 && B[i][j] != 0) {
39+
if(T[pivots[i]][pivots[j]] != 0 && Bi[i][j] != 0) {
4040
ans.emplace_back(pivots[i], pivots[j]);
41-
B.eliminate<gauss_mode::reverse>(i, j);
42-
B.eliminate<gauss_mode::reverse>(j, i);
43-
B.normalize();
44-
B[i] *= 0;
45-
B[j] *= 0;
41+
Bi.eliminate<gauss_mode::reverse>(i, j);
42+
Bi.eliminate<gauss_mode::reverse>(j, i);
43+
Bi.normalize();
44+
Bi[i] *= 0;
45+
Bi[j] *= 0;
4646
}
4747
}
4848
}

0 commit comments

Comments
 (0)