Asa's CP Library

a01sa01to's competitive programming library. Requires C++20 or higher with GCC. This documentation is automatically generated by online-judge-tools/verification-helper

View the Project on GitHub a01sa01to/cp-library

:heavy_check_mark: 行列式
(library/matrix/determinant.hpp)

行列式を求める。

掃き出し法を用いて上三角行列に変形し、対角成分の積をとることで行列式を求める。 以下の性質を利用。

計算量は $O(n^3)$。

Depends on

Verified with

Code

#pragma once

#include <cassert>
#include <cstddef>
#include <utility>
#include <valarray>
using namespace std;

#include "../_internal/modint-base.hpp"
#include "../data-structure/matrix.hpp"

namespace asalib {
  namespace matrix {
    template<_internal::numeric_like T>
    inline constexpr T Matrix<T>::determinant() const { return determinant<T>(); }

    template<_internal::numeric_like T>
    template<_internal::numeric_like U>
    inline constexpr U Matrix<T>::determinant() const {
      assert(_n_row == _n_col);
      valarray<valarray<U>> t(_data);
      U res = 1;
      for (size_t i = 0; i < _n_row; ++i) {
        if (t[i][i] == 0) {
          // ピボットが 0 のとき、他の行と交換
          for (size_t j = i + 1; j < _n_row; ++j) {
            if (t[j][i] != 0) {
              swap(t[j], t[i]);
              res *= -1;
              break;
            }
          }
        }
        if (t[i][i] == 0) return 0;
        // 掃き出し
        for (size_t j = i + 1; j < _n_row; ++j) {
          if (t[j][i] == 0) continue;
          try {
            U r = t[j][i] / t[i][i];
            for (size_t k = i; k < _n_col; ++k) t[j][k] -= r * t[i][k];
          }
          catch (...) {
            // t[i][i] != 0 なのでゼロ割りは発生しない -> modint で逆元がないときにこっちに来る
            assert(_internal::is_modint<U>);
            // 以下の方法は modint 以外でも使える (はず) だが、 q 計算で .val してるので try-catch にしてやる
            // 拡張ユークリッドして、 A * (t[i][i], t[j][i]) = (gcd, 0) となるような 2x2 の A を作ってやる
            // | a  b | | tii | = | x |
            // | c  d | | tji |   | y |
            // となるように保持する
            // 初期値は a = 1, b = 0, x = tii; c = 0, d = 1, y = tji;
            U a = 1, b = 0, c = 0, d = 1, x = t[i][i], y = t[j][i];
            bool neg = false;
            while (y != 0) {
              // ただの数だと思って計算するといいらしい?
              U q = x.val() / y.val();
              U z = x - q * y;
              U e = a - q * c, f = b - q * d;
              x = y, y = z, a = c, b = d, c = e, d = f;
              neg = !neg;
            }
            if (neg) c = -c, d = -d;
            assert(a * t[i][i] + b * t[j][i] == x);
            assert(c * t[i][i] + d * t[j][i] == 0);
            valarray<U> tmpi = t[i], tmpj = t[j];
            for (size_t k = i; k < _n_col; ++k) {
              t[i][k] = a * tmpi[k] + b * tmpj[k];
              t[j][k] = c * tmpi[k] + d * tmpj[k];
            }
            assert(t[i][i] == x);
            assert(t[j][i] == 0);
          }
        }
      }
      for (size_t i = 0; i < _n_row; ++i) res *= t[i][i];
      return res;
    }
  }  // namespace matrix
}  // namespace asalib
#line 2 "library/matrix/determinant.hpp"

#include <cassert>
#include <cstddef>
#include <utility>
#include <valarray>
using namespace std;

#line 2 "library/_internal/modint-base.hpp"

#include <concepts>
#include <type_traits>
using namespace std;

namespace asalib {
  namespace _internal {
    class modint_base {};

    template<typename T>
    concept is_modint = is_base_of_v<modint_base, T>;
  }  // namespace _internal
}  // namespace asalib
#line 2 "library/data-structure/matrix.hpp"

#line 7 "library/data-structure/matrix.hpp"
using namespace std;

#line 2 "library/_internal/types.hpp"

#line 4 "library/_internal/types.hpp"
using namespace std;

#line 7 "library/_internal/types.hpp"

namespace asalib {
  namespace _internal {
    // ---------- concept definition ---------- //
    template<class T>
    concept integral_like = integral<T> || is_modint<T>;

    template<class T>
    concept floating_like = floating_point<T>;

    template<class T>
    concept numeric_like = integral_like<T> || floating_like<T>;

    // ---------- function definition ---------- //
    template<class T>
    T plus(T a, T b) { return a + b; }

    template<class T>
    T minus(T a, T b) { return a - b; }

    // ---------- constant definition ---------- //
    template<class T>
    T zero() { return 0; }
  }  // namespace _internal
}  // namespace asalib
#line 10 "library/data-structure/matrix.hpp"

namespace asalib {
  namespace matrix {
    template<_internal::numeric_like T>
    class Matrix {
      public:
      constexpr Matrix(): _n_row(0), _n_col(0) {};
      constexpr Matrix(size_t n_row, size_t n_col): _n_row(n_row), _n_col(n_col) {
        _data.resize(n_row, valarray<T>(n_col));
      };
      constexpr Matrix(size_t n_row, size_t n_col, T x): _n_row(n_row), _n_col(n_col) {
        _data.resize(n_row, valarray<T>(n_col, x));
      };

      inline constexpr T& at(size_t i, size_t j) {
        assert(i < _n_row);
        assert(j < _n_col);
        return _data[i][j];
      }
      inline constexpr T at(size_t i, size_t j) const {
        assert(i < _n_row);
        assert(j < _n_col);
        return _data[i][j];
      }

      inline constexpr Matrix& operator+=(const T& x) {
        _data += x;
        return *this;
      }
      inline constexpr Matrix& operator-=(const T& x) {
        _data -= x;
        return *this;
      }
      inline constexpr Matrix& operator*=(const T& x) {
        _data *= x;
        return *this;
      }
      inline constexpr Matrix& operator/=(const T& x) {
        _data /= x;
        return *this;
      }
      inline constexpr Matrix& operator%=(const T& x) {
        _data %= x;
        return *this;
      }
      inline constexpr Matrix operator+(const T& x) const { return Matrix(*this) += x; }
      inline constexpr Matrix operator-(const T& x) const { return Matrix(*this) -= x; }
      inline constexpr Matrix operator*(const T& x) const { return Matrix(*this) *= x; }
      inline constexpr Matrix operator/(const T& x) const { return Matrix(*this) /= x; }
      inline constexpr Matrix operator%(const T& x) const { return Matrix(*this) %= x; }

      inline constexpr Matrix& operator+=(const Matrix& x) {
        assert(_n_row == x._n_row);
        assert(_n_col == x._n_col);
        _data += x._data;
        return *this;
      }
      inline constexpr Matrix& operator-=(const Matrix& x) {
        assert(_n_row == x._n_row);
        assert(_n_col == x._n_col);
        _data -= x._data;
        return *this;
      }
      inline constexpr Matrix& operator*=(const Matrix& x) {
        assert(_n_col == x._n_row);
        Matrix res(_n_row, x._n_col);
        for (size_t i = 0; i < _n_row; ++i) {
          for (size_t k = 0; k < _n_col; ++k) {
            for (size_t j = 0; j < x._n_col; ++j) {
              res._data[i][j] += _data[i][k] * x._data[k][j];
            }
          }
        }
        return *this = res;
      }
      inline constexpr Matrix operator+(const Matrix& x) const { return Matrix(*this) += x; }
      inline constexpr Matrix operator-(const Matrix& x) const { return Matrix(*this) -= x; }
      inline constexpr Matrix operator*(const Matrix& x) const { return Matrix(*this) *= x; }

      inline constexpr bool operator==(const Matrix& x) const { return _n_row == x._n_row && _n_col == x._n_col && _data == x._data; }
      inline constexpr bool operator!=(const Matrix& x) const { return !(*this == x); }
      inline constexpr bool operator<(const Matrix& x) const { return _data < x._data; }

      inline constexpr Matrix transpose() const {
        Matrix res(_n_col, _n_row);
        for (size_t i = 0; i < _n_row; ++i) {
          for (size_t j = 0; j < _n_col; ++j) {
            res._data[j][i] = _data[i][j];
          }
        }
        return res;
      }

      template<integral U>
      inline constexpr Matrix pow(U x) const {
        assert(_n_row == _n_col);
        Matrix res = I(_n_row);
        Matrix a(*this);
        while (x) {
          if (x & 1) res *= a;
          a *= a;
          x >>= 1;
        }
        return res;
      }

      inline static constexpr Matrix I(size_t n) {
        Matrix res(n, n);
        for (size_t i = 0; i < n; ++i) {
          res._data[i][i] = 1;
        }
        return res;
      }

      inline constexpr size_t n_row() const { return _n_row; }
      inline constexpr size_t n_col() const { return _n_col; }

      private:
      size_t _n_row, _n_col;
      valarray<valarray<T>> _data;

      public:
      // ---------- prototype ---------- //
      inline constexpr T determinant() const;
      template<_internal::numeric_like U>
      inline constexpr U determinant() const;
    };
  }  // namespace matrix
}  // namespace asalib
#line 11 "library/matrix/determinant.hpp"

namespace asalib {
  namespace matrix {
    template<_internal::numeric_like T>
    inline constexpr T Matrix<T>::determinant() const { return determinant<T>(); }

    template<_internal::numeric_like T>
    template<_internal::numeric_like U>
    inline constexpr U Matrix<T>::determinant() const {
      assert(_n_row == _n_col);
      valarray<valarray<U>> t(_data);
      U res = 1;
      for (size_t i = 0; i < _n_row; ++i) {
        if (t[i][i] == 0) {
          // ピボットが 0 のとき、他の行と交換
          for (size_t j = i + 1; j < _n_row; ++j) {
            if (t[j][i] != 0) {
              swap(t[j], t[i]);
              res *= -1;
              break;
            }
          }
        }
        if (t[i][i] == 0) return 0;
        // 掃き出し
        for (size_t j = i + 1; j < _n_row; ++j) {
          if (t[j][i] == 0) continue;
          try {
            U r = t[j][i] / t[i][i];
            for (size_t k = i; k < _n_col; ++k) t[j][k] -= r * t[i][k];
          }
          catch (...) {
            // t[i][i] != 0 なのでゼロ割りは発生しない -> modint で逆元がないときにこっちに来る
            assert(_internal::is_modint<U>);
            // 以下の方法は modint 以外でも使える (はず) だが、 q 計算で .val してるので try-catch にしてやる
            // 拡張ユークリッドして、 A * (t[i][i], t[j][i]) = (gcd, 0) となるような 2x2 の A を作ってやる
            // | a  b | | tii | = | x |
            // | c  d | | tji |   | y |
            // となるように保持する
            // 初期値は a = 1, b = 0, x = tii; c = 0, d = 1, y = tji;
            U a = 1, b = 0, c = 0, d = 1, x = t[i][i], y = t[j][i];
            bool neg = false;
            while (y != 0) {
              // ただの数だと思って計算するといいらしい?
              U q = x.val() / y.val();
              U z = x - q * y;
              U e = a - q * c, f = b - q * d;
              x = y, y = z, a = c, b = d, c = e, d = f;
              neg = !neg;
            }
            if (neg) c = -c, d = -d;
            assert(a * t[i][i] + b * t[j][i] == x);
            assert(c * t[i][i] + d * t[j][i] == 0);
            valarray<U> tmpi = t[i], tmpj = t[j];
            for (size_t k = i; k < _n_col; ++k) {
              t[i][k] = a * tmpi[k] + b * tmpj[k];
              t[j][k] = c * tmpi[k] + d * tmpj[k];
            }
            assert(t[i][i] == x);
            assert(t[j][i] == 0);
          }
        }
      }
      for (size_t i = 0; i < _n_row; ++i) res *= t[i][i];
      return res;
    }
  }  // namespace matrix
}  // namespace asalib
Back to top page