cp-library

競技プログラミング用 C++ ライブラリ

View the Project on GitHub qandori/cp-library

:warning: 行列(軽量版)

math/matrix_light.hpp · GitHub で見る

64 KiBサイト · 軽量実装

この項目の軽量実装は LightMatrix<T> です。以下の使用例・API一覧は共有ヘッダーの説明です。

LightMatrix<T> は 行列 と同じ操作を使える軽量実装です。通常版と同じ共通コードを使い、数値型専用の行列積と Frobenius 分解は読み込みません。通常版の Matrix<T> と同じソースで併用できます。

#include "lib/math/matrix_light.hpp"
#include "lib/fps/fps_light.hpp"

using M = LightMatrix<light_fps>;
M a{ {light_fps{1}, light_fps{0, 1}},
     {light_fps{0, 1}, light_fps{1}} };
int degree = 8;
auto b = a.pow(1000000000000000000ULL, [degree](M &m) {
    for (int i = 0; i < m.rows(); ++i)
        for (auto &f : m[i])
            if (f.size() > std::size_t(degree)) f.resize(degree);
});

この例は \(x^8\) を法として FPS を要素とする行列を累乗します。pow(k,normalize) は単位行列・入力行列と、各積の結果に normalize を呼びます。FPS の次数は積のたびに打ち切るため、大きな指数も扱えます。通常版でも Matrix<fps> と同じ書き方ができます。

型 T に関する条件や、累乗以外の API は 通常版 を参照してください。固定法 modint の行列で速度を重視する場合は通常版を使います。通常版の行列単独も 64 KiB 以内に収まります。

行列積 \(n\times k\) と \(k\times m\) は \(O(nkm)\)、正方行列の累乗は \(O(n^3\log k)\)、追加空間は \(O(nk+km+nm)\) です。要素の演算・コピーを \(O(1)\) とします。FPS を要素にするときは、その演算の計算量を掛けます。normalize の処理時間は別途必要です。

依存ライブラリ

コード

#ifndef MATRIX_LIGHT_HPP
#define MATRIX_LIGHT_HPP

#include "../components/matrix_core.hpp"

namespace matrix_detail {
template <class T>
struct PlainMatrixArithmetic {
	static constexpr bool modular = false;
	template <class F>
	static auto field(std::vector<T> &a, F &&f) {
		static_assert(!integer<T>);
		return f.template operator()<Field<T>>(a);
	}
	static std::vector<T> multiply(const std::vector<T> &a, const std::vector<T> &b, int n, int inner, int m) {
		return basic_multiply(a, b, n, inner, m);
	}
	static std::optional<std::vector<T>> power(const std::vector<T> &, int, std::uint64_t) { return std::nullopt; }
};
}

template <class T>
using LightMatrix = Matrix<T, matrix_detail::PlainMatrixArithmetic<T>>;

#endif
Back to top page