sirkit-cpp-library

競技プログラミング向けのC++23ライブラリ。API、使用例、検証結果を確認できます。

View the Project on GitHub reinsirk/sirkit-cpp-library

BinaryMatrix

Math/Binary_Matrix.cpp · ソース · 文書 Last Commit

通常版・コンパイラ共通 · この版の一覧へ

通常版・GCC専用 · この版の一覧へ

通常版・Clang専用 · この版の一覧へ

通常版・MSVC専用 · この版の一覧へ

速度優先版・コンパイラ共通 · この版の一覧へ

速度優先版・GCC専用 · この版の一覧へ

速度優先版・Clang専用 · この版の一覧へ

速度優先版・MSVC専用 · この版の一覧へ

BinaryMatrixは0/1の行列です。要素の和をXOR、積をANDとして計算するGF(2)上で、行列積・階数・逆行列・連立方程式を扱います。Mintは不要です。使用例を参照してください。

R行C列、r=min(R,C)、W=ceil(C/64)とします。積では(R,M)*(M,K)の形を用います。

API

BinaryMatrix::BinaryMatrix

explicit BinaryMatrix(std::size_t rows = 0, std::size_t cols = 0);
BinaryMatrix(const BinaryMatrix&);
BinaryMatrix(BinaryMatrix&& other) noexcept;

指定した形の全0行列を作ります。0×n・n×0でも行数と列数を保持します。

制約: 共通の型・入力条件を満たすこと。

計算量: R行C列にO(1+R ceil(C/64))時間・領域。移動構築・swapはO(1)。

BinaryMatrix::operator=

BinaryMatrix& operator=(const BinaryMatrix& other);
BinaryMatrix& operator=(BinaryMatrix&& other) noexcept;

コピーまたは移動で内容を置き換え、自身への参照を返します。

制約: 共通の型・入力条件を満たすこと。

計算量: R行C列にO(1+R ceil(C/64))時間・領域。移動構築・swapはO(1)。

BinaryMatrix::swap

void swap(BinaryMatrix& other) noexcept;
friend void swap(BinaryMatrix& a, BinaryMatrix& b) noexcept;

内容と所有する領域を交換します。

制約: 共通の型・入力条件を満たすこと。

計算量: O(1)。

BinaryMatrix::rows

std::size_t rows() const noexcept;

行数を返します。

制約: なし。

計算量: O(1)。

BinaryMatrix::cols

std::size_t cols() const noexcept;

列数を返します。

制約: なし。

計算量: O(1)。

BinaryMatrix::empty

bool empty() const noexcept;

空ならtrueを返します。

制約: なし。

計算量: O(1)。

BinaryMatrix::row_words

std::span<const std::uint64_t> row_words(std::size_t row) const;

行を読み取り専用のword spanで返します。word iのbit jは列64i+jに対応します。

制約: 行添字が範囲内。viewは所有権移動・再構築まで有効。

計算量: O(1)。

BinaryMatrix::test

bool test(std::size_t row, std::size_t col) const;

要素をboolで返す。

制約: 行・列添字が範囲内。

計算量: O(1)。

BinaryMatrix::operator()

bool operator()(std::size_t row, std::size_t col) const;

指定した要素を返します。

制約: r<rows()、c<cols()。

計算量: O(1)。

BinaryMatrix::set

BinaryMatrix& set(std::size_t row, std::size_t col, bool value = true);

要素を変更し、自身への参照を返す。

制約: 更新する添字が範囲内。

計算量: O(1)。

BinaryMatrix::flip

BinaryMatrix& flip(std::size_t row, std::size_t col);

要素を変更し、自身への参照を返す。

制約: 行・列添字が範囲内。

計算量: O(1)。

BinaryMatrix::swap_rows

void swap_rows(std::size_t a, std::size_t b);

指定した2行を交換します。

制約: 共通の型・入力条件を満たすこと。

計算量: W=ceil(C/64)としてO(W)。

BinaryMatrix::xor_rows

void xor_rows(std::size_t target, std::size_t source, std::size_t first_col = 0);

指定列以降だけXORする。自己XORも可。

制約: 共通の型・入力条件を満たすこと。

計算量: W=ceil(C/64)としてO(W)。

BinaryMatrix::identity

static BinaryMatrix identity(std::size_t n);

n次単位行列を返します。

制約: n次行列を確保できる容量。

計算量: O(1+n ceil(n/64))時間・領域。

BinaryMatrix::transpose

BinaryMatrix transpose() const;

転置した行列を返します。

制約: 共通の型・入力条件を満たすこと。

計算量: O(1+RC)時間。

BinaryMatrix::multiply

BinaryMatrix multiply(const BinaryMatrix& other) const;

行列積を求めます。自己積の代入にも使えます。

制約: 左行列の列数と右行列の行数が同じ。

計算量: (R,M)*(M,K)にO(1+MK+R ceil(K/64)+RK ceil(M/64))時間。

BinaryMatrix::operator*

BinaryMatrix operator*(const BinaryMatrix& other) const;

積を返します。

制約: 左行列の列数と右行列の行数が同じ。

計算量: (R,M)*(M,K)にO(1+MK+R ceil(K/64)+RK ceil(M/64))時間。

BinaryMatrix::operator*=

BinaryMatrix& operator*=(const BinaryMatrix& other);

乗算して自身を更新します。

制約: 左行列の列数と右行列の行数が同じ。

計算量: (R,M)*(M,K)にO(1+MK+R ceil(K/64)+RK ceil(M/64))時間。

BinaryMatrix::operator+=

BinaryMatrix& operator+=(const BinaryMatrix& other);

同形行列のGF(2)上の和を自身に代入して自身への参照を返します。

制約: 両行列の行数・列数が同じ。

計算量: R行C列にO(1+R ceil(C/64))時間・領域。移動構築・swapはO(1)。

BinaryMatrix::operator^=

BinaryMatrix& operator^=(const BinaryMatrix& other);

同形行列のGF(2)上の和を自身に代入して自身への参照を返します。

制約: 両行列の行数・列数が同じ。

計算量: R行C列にO(1+R ceil(C/64))時間・領域。移動構築・swapはO(1)。

BinaryMatrix::operator+

friend BinaryMatrix operator+(BinaryMatrix a, const BinaryMatrix& b);

同形行列のGF(2)上の和を新しい行列で返します。

制約: 両行列の行数・列数が同じ。

計算量: R行C列にO(1+R ceil(C/64))時間・領域。移動構築・swapはO(1)。

BinaryMatrix::operator^

friend BinaryMatrix operator^(BinaryMatrix a, const BinaryMatrix& b);

同形行列のGF(2)上の和を新しい行列で返します。

制約: 両行列の行数・列数が同じ。

計算量: R行C列にO(1+R ceil(C/64))時間・領域。移動構築・swapはO(1)。

BinaryMatrix::operator==

bool operator==(const BinaryMatrix& other) const noexcept;

値と形が等しいかを返します。

制約: 共通の型・入力条件を満たすこと。

計算量: R行C列にO(1+R ceil(C/64))時間・領域。移動構築・swapはO(1)。

BinaryMatrix::pow

BinaryMatrix pow(std::uint64_t exponent) const;

正方行列の非負整数乗を返します。指数が0なら単位行列を返します。

制約: 正方行列。powの指数は非負。

計算量: O(log(k+1))回の行列積。

BinaryMatrix::rank

std::size_t rank() const;

階数を返します。

制約: なし。

計算量: r=min(R,C)、W=ceil(C/64)としてO(1+RC+RrW)時間。

BinaryMatrix::determinant

bool determinant() const;

正方行列の行列式をboolで返します。0×0の行列式は1です。

制約: 正方行列。

計算量: r=min(R,C)、W=ceil(C/64)としてO(1+RC+RrW)時間。

BinaryMatrix::inverse

std::optional<BinaryMatrix> inverse() const;

逆行列をoptionalで返します。非正則ならnullopt、0×0なら空の単位行列を返します。

制約: 正方行列。

計算量: r=min(R,C)、W=ceil(C/64)としてO(1+RC+RrW)時間。

BinaryMatrix::solve

std::optional<LinearSolution> solve(std::span<const std::uint8_t> rhs) const;

Ax=rhsの解をoptionalで返します。解がなければnulloptです。rhsは行数と同じ個数のuint8_tの0/1で指定します。

制約: 共通の型・入力条件を満たすこと。

計算量: 消去O(1+RC+RrW)に核の生成O(R+C+C(C-rank))を加える。

BinaryMatrix::reset

void reset(std::size_t rows = 0, std::size_t cols = 0);

全要素が0の行列に初期化し直します。

制約: 共通の型・入力条件を満たすこと。

計算量: R行C列にO(1+R ceil(C/64))時間・領域。移動構築・swapはO(1)。

BinaryMatrix::clear

void clear() noexcept;

内容を空に戻します。

制約: 共通の型・入力条件を満たすこと。

計算量: R行C列にO(1+R ceil(C/64))時間・領域。移動構築・swapはO(1)。

LinearSolution::LinearSolution

LinearSolution();
LinearSolution(std::vector<std::uint8_t> value, BinaryMatrix basis, std::vector<std::size_t> pivots);
LinearSolution(const LinearSolution&);
LinearSolution(LinearSolution&& other) noexcept;

空または指定した入力から構築します。コピーは独立、移動は所有権を移します。

制約: なし。

計算量: コピーはparticular・pivot_columns・kernelの保持量に比例。移動構築・swapはO(1)、代入は旧状態の破棄も加える。

LinearSolution::operator=

LinearSolution& operator=(const LinearSolution& other);
LinearSolution& operator=(LinearSolution&& other) noexcept;

コピーまたは移動で内容を置き換え、自身への参照を返します。

制約: なし。

計算量: コピーはparticular・pivot_columns・kernelの保持量に比例。移動構築・swapはO(1)、代入は旧状態の破棄も加える。

LinearSolution::swap

void swap(LinearSolution& other) noexcept;
friend void swap(LinearSolution& a, LinearSolution& b) noexcept;

内容と所有する領域を交換します。

制約: なし。

計算量: コピーはparticular・pivot_columns・kernelの保持量に比例。移動構築・swapはO(1)、代入は旧状態の破棄も加える。

BinaryMatrix a(2,3);
a.set(0,0).set(0,2).set(1,1).set(1,2);
auto result = a.solve(std::vector<std::uint8_t>{1,0});
// 特解は(1,0,0)、核の基底は(1,1,1)。

解のparticularは列数個の特解、kernelは各行が核の基底となる(列数−rank)行の行列、pivot_columnsは消去のピボット列です。任意の解は、特解と核基底の任意の組合せをXORして作れます。基底の具体的な形に依存せず使ってください。

0行では全変数が自由となり、特解は全0・核は単位行列です。0列ではrhsが全0の場合だけ解を持ちます。最初の非0で終了するため、後続の未参照rhsまで検査する保証はありません。

計算量・所有と検査

R行C列、W=ceil(C/64)、r=min(R,C)とします。行をまとめて1本のvectorで保持し、格納はR*W語です。構築・コピーはO(1+RW)、要素操作はO(1)、行操作は最悪O(W)、転置はO(1+RC)です。

R×MとM×Kの積はO(1+MK+R ceil(K/64)+RK ceil(M/64))時間で、転置と結果の2行列を追加確保します。rankの消去はO(1+RC+RrW)時間、inverseは正方行列で同規模です。solveはこれにO(R+C+C(C−rank))時間を追加し、核出力に(C−rank)ceil(C/64)語、特解・ピボット列にO(C)領域を使います。powはO(log(k+1))回の行列積です。

全てのconst計算は入力と既存viewを保ちます。コピーは独立し、コピー代入・reset・積代入とLinearSolutionのコピー代入は、確保失敗時に旧内容を維持します。move/swapはO(1)、move元は行列なら0×0、解なら全フィールド空です。row_wordsのviewは成功したreset・clear・代入・所有権移動まで有効で、通常の要素変更は同じ領域に反映されます。

SKIP_RUNTIME_CHECKSは番号・形・rhs長と参照したrhsの0/1検査を除きます。内部容量積の保護、0次元・0係数の判定は維持します。bit kernelはDynamicBitsetと独立ガードで共有し、生成器で単独貼付版へ同期します。SIRKIT_DISABLE_SIMDで追加のCPU判定と専用経路を除外できます。

VerifyはLibrary Checkerの積・階数・行列式・逆行列・連立方程式です。行操作・累乗・境界・所有権は独立ローカル参照で補います。

ソースのAPI注記
BinaryMatrix(rows=0,cols=0): 全0行列。O(rows*ceil(cols/64))時間/領域。GF(2)上の要素0/1を扱う。
rows()/cols()/empty(): 行数/列数/要素が0個か。row_words(row): 列0を最下位bitとするconst word span。
test(row,col)/operator()(row,col): bool取得。set(row,col,value=true)/flip(row,col): 要素変更、*thisを返す。
swap_rows(a,b), xor_rows(target,source,first_col=0): 行交換/first_col以降だけの行XOR。自己XOR可。
transpose(): 転置。multiply(other)/operator*: 積。operator*=は自己参照可。pow(uint64_t): 正方行列の累乗。
identity(n): 単位行列。+= / + / ^= / ^は同形行列のGF(2)和。==は形と全要素の一致。
rank(): 階数。determinant(): 正方行列の行列式bool。0x0の行列式は1。
inverse(): optional<BinaryMatrix>、非正則ならnullopt。0x0は0x0単位行列を返す。
solve(span<const uint8_t> rhs): Ax=rhsのoptional<LinearSolution>、不能ならnullopt。rhsは行数個の0/1。
LinearSolution {particular,kernel,pivot_columns}: particularは列数個のuint8_t特解、
  kernelは各行が核の基底となる(列数-rank)x列数の行列。任意解は特解と基底行の線形結合。
  pivot_columnsはRREFのpivot列。0行/0列も可。0行では全変数が自由、0列ではrhsが全0の場合のみ可。
reset(rows=0,cols=0)/clear(): 再初期化/0x0。copyは独立所有・代入強保証、move元は0x0で再利用可。
swapはO(1)。set/test/flip/形照会はO(1)、行操作はO(ceil(cols/64))、転置O(rows*cols)。
AxBの積はO(1+B.rows*B.cols + A.rows*ceil(B.cols/64) + A.rows*B.cols*ceil(A.cols/64))。
累乗は行列積O(log(k+1))回。内側0次元でも結果の全0領域は確保する。
rank/inverseの消去は最悪O(1+rows*cols + rows*min(rows,cols)*ceil(cols/64))時間。元行列を変更しない。
solveは上記にO(rows+cols+cols*(cols-rank))時間を追加、核は(cols-rank)*ceil(cols/64)語。
LinearSolutionも独立copy/代入強保証、move元の全フィールドは空。swapはO(1)。
確保失敗時は元の内容/viewを維持。viewは成功したreset/clear/代入/所有権移動まで有効。
番号・形・rhs長/参照したrhsの0/1検査はSKIP_RUNTIME_CHECKSで除外。容量保護・数学的0判定は維持。
0列のsolveは非0のrhsを見つけた時点で終了し、それ以降のrhsは検査しない。
SIRKIT_DISABLE_SIMDは共有bit kernelの追加CPU判定/専用実装を除く。消去/転置に独自SIMDは使わない。
Verifyプログラムと検証結果

Verifyプログラム

通常版の検証結果です。

問題 プログラム 現行ソースの状態 提出結果
Determinant of Matrix (Mod 2) binary_matrix_det.cpp 未提出 —
Inverse Matrix (Mod 2) binary_matrix_inverse.cpp 未提出 —
Matrix Product (Mod 2) binary_matrix_product.cpp 未提出 —
Rank of Matrix (Mod 2) binary_matrix_rank.cpp 未提出 —
System of Linear Equations (Mod 2) binary_matrix_solve.cpp 未提出 —

✓ 現行ACには、提出本文を照合したACと、利用者が現行版の提出を確認したAtCoderのACを含めます。

ローカル・CI検査

検査 状態
正常系 未実施
失敗系 未測定
Library Checker公式ケース 未測定
性能測定 未実施
ASan/UBSan 未実施
カバレッジ 未実施

到達不能と証明した箇所を除き、通常版本体のカバレッジは行・直接分岐とも100%が合格条件です。未計測の場合も不合格です。

実行条件・件数・測定結果 · 結果JSON

Verified with

Code

// SPDX-License-Identifier: CC0-1.0
// 参考: https://nyaannyaan.github.io/library/matrix/f2-matrix.hpp
// GF(2)の掃き出し法・機能選定を参考に独立実装。内部bit kernelはDynamicBitsetと同一guardで共有。
// ドキュメント: https://github.com/reinsirk/sirkit-cpp-library/blob/main/Document/binary_matrix.md
// API一覧
// BinaryMatrix(rows=0,cols=0): 全0行列。O(rows*ceil(cols/64))時間/領域。GF(2)上の要素0/1を扱う。
// rows()/cols()/empty(): 行数/列数/要素が0個か。row_words(row): 列0を最下位bitとするconst word span。
// test(row,col)/operator()(row,col): bool取得。set(row,col,value=true)/flip(row,col): 要素変更、*thisを返す。
// swap_rows(a,b), xor_rows(target,source,first_col=0): 行交換/first_col以降だけの行XOR。自己XOR可。
// transpose(): 転置。multiply(other)/operator*: 積。operator*=は自己参照可。pow(uint64_t): 正方行列の累乗。
// identity(n): 単位行列。+= / + / ^= / ^は同形行列のGF(2)和。==は形と全要素の一致。
// rank(): 階数。determinant(): 正方行列の行列式bool。0x0の行列式は1。
// inverse(): optional<BinaryMatrix>、非正則ならnullopt。0x0は0x0単位行列を返す。
// solve(span<const uint8_t> rhs): Ax=rhsのoptional<LinearSolution>、不能ならnullopt。rhsは行数個の0/1。
// LinearSolution {particular,kernel,pivot_columns}: particularは列数個のuint8_t特解、
//   kernelは各行が核の基底となる(列数-rank)x列数の行列。任意解は特解と基底行の線形結合。
//   pivot_columnsはRREFのpivot列。0行/0列も可。0行では全変数が自由、0列ではrhsが全0の場合のみ可。
// reset(rows=0,cols=0)/clear(): 再初期化/0x0。copyは独立所有・代入強保証、move元は0x0で再利用可。
// swapはO(1)。set/test/flip/形照会はO(1)、行操作はO(ceil(cols/64))、転置O(rows*cols)。
// AxBの積はO(1+B.rows*B.cols + A.rows*ceil(B.cols/64) + A.rows*B.cols*ceil(A.cols/64))。
// 累乗は行列積O(log(k+1))回。内側0次元でも結果の全0領域は確保する。
// rank/inverseの消去は最悪O(1+rows*cols + rows*min(rows,cols)*ceil(cols/64))時間。元行列を変更しない。
// solveは上記にO(rows+cols+cols*(cols-rank))時間を追加、核は(cols-rank)*ceil(cols/64)語。
// LinearSolutionも独立copy/代入強保証、move元の全フィールドは空。swapはO(1)。
// 確保失敗時は元の内容/viewを維持。viewは成功したreset/clear/代入/所有権移動まで有効。
// 番号・形・rhs長/参照したrhsの0/1検査はSKIP_RUNTIME_CHECKSで除外。容量保護・数学的0判定は維持。
// 0列のsolveは非0のrhsを見つけた時点で終了し、それ以降のrhsは検査しない。
// SIRKIT_DISABLE_SIMDは共有bit kernelの追加CPU判定/専用実装を除く。消去/転置に独自SIMDは使わない。


// SIRKIT_NAMESPACE_V1: 公開APIはsirkit、既存のgeoはsirkit::geo、内部部品はsirkit::detail。
#include <algorithm>
#include <bit>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <span>
#include <stdexcept>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
#if !defined(SIRKIT_DISABLE_SIMD) && (defined(__x86_64__) || defined(__i386__)) && (defined(__GNUC__) || defined(__clang__))
#include <immintrin.h>
#endif


// SIRKIT_NAMESPACE_OPEN_V1
namespace sirkit {
#ifndef SIRKIT_DYNAMIC_BITSET_WORD_OPERATIONS_DEFINED
#define SIRKIT_DYNAMIC_BITSET_WORD_OPERATIONS_DEFINED
namespace /*SIRKIT_NS_REWRITE_V1:D:cmVpbnNpcms6OmRldGFpbA==*/detail/*SIRKIT_NS_REWRITE_END_V1*/ {
inline unsigned bitset_word_popcount(std::uint64_t x) noexcept {
    x -= (x >> 1) & UINT64_C(0x5555555555555555);
    x = (x & UINT64_C(0x3333333333333333)) + ((x >> 2) & UINT64_C(0x3333333333333333));
    x = (x + (x >> 4)) & UINT64_C(0x0f0f0f0f0f0f0f0f);
    return static_cast<unsigned>((x * UINT64_C(0x0101010101010101)) >> 56);
}
inline std::size_t bitset_count_words_scalar(const std::uint64_t* words, std::size_t count) noexcept {
    std::size_t result = 0;
    for (std::size_t i = 0; i < count; ++i) result += bitset_word_popcount(words[i]);
    return result;
}
inline std::size_t bitset_intersection_words_scalar(const std::uint64_t* a, const std::uint64_t* b, std::size_t count) noexcept {
    std::size_t result = 0;
    for (std::size_t i = 0; i < count; ++i) result += bitset_word_popcount(a[i] & b[i]);
    return result;
}
inline bool bitset_intersection_parity_words_scalar(const std::uint64_t* a, const std::uint64_t* b, std::size_t count) noexcept {
    std::uint64_t value = 0;
    for (std::size_t i = 0; i < count; ++i) value ^= a[i] & b[i];
    return (bitset_word_popcount(value) & 1) != 0;
}

#if !defined(SIRKIT_DISABLE_SIMD) && (defined(__x86_64__) || defined(__i386__)) && (defined(__GNUC__) || defined(__clang__))

__attribute__((target("popcnt"))) inline std::size_t bitset_count_words_popcnt(const std::uint64_t* a,std::size_t n) noexcept {
    std::size_t s0=0,s1=0,s2=0,s3=0,i=0;
    for(;n-i>=4;i+=4){s0+=static_cast<unsigned>(__builtin_popcountll(a[i]));s1+=static_cast<unsigned>(__builtin_popcountll(a[i+1]));s2+=static_cast<unsigned>(__builtin_popcountll(a[i+2]));s3+=static_cast<unsigned>(__builtin_popcountll(a[i+3]));}
    for(;i<n;++i)s0+=static_cast<unsigned>(__builtin_popcountll(a[i]));
    return s0+s1+s2+s3;
}
__attribute__((target("popcnt"))) inline std::size_t bitset_intersection_words_popcnt(const std::uint64_t* a,const std::uint64_t* b,std::size_t n) noexcept {
    std::size_t s0=0,s1=0,s2=0,s3=0,i=0;
    for(;n-i>=4;i+=4){s0+=static_cast<unsigned>(__builtin_popcountll(a[i]&b[i]));s1+=static_cast<unsigned>(__builtin_popcountll(a[i+1]&b[i+1]));s2+=static_cast<unsigned>(__builtin_popcountll(a[i+2]&b[i+2]));s3+=static_cast<unsigned>(__builtin_popcountll(a[i+3]&b[i+3]));}
    for(;i<n;++i)s0+=static_cast<unsigned>(__builtin_popcountll(a[i]&b[i]));
    return s0+s1+s2+s3;
}
__attribute__((target("avx2,popcnt"))) inline std::size_t bitset_count_words_avx2(const std::uint64_t* a,std::size_t n) noexcept {
    const auto table=_mm256_setr_epi8(0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4,0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4);
    const auto mask=_mm256_set1_epi8(15),zero=_mm256_setzero_si256();auto total=zero;std::size_t i=0;
    for(;n-i>=4;i+=4){const auto x=_mm256_loadu_si256(reinterpret_cast<const __m256i*>(a+i));const auto lo=_mm256_shuffle_epi8(table,_mm256_and_si256(x,mask));const auto hi=_mm256_shuffle_epi8(table,_mm256_and_si256(_mm256_srli_epi16(x,4),mask));total=_mm256_add_epi64(total,_mm256_sad_epu8(_mm256_add_epi8(lo,hi),zero));}
    alignas(32) std::uint64_t lanes[4];_mm256_store_si256(reinterpret_cast<__m256i*>(lanes),total);auto result=lanes[0]+lanes[1]+lanes[2]+lanes[3];
    for(;i<n;++i)result+=static_cast<unsigned>(__builtin_popcountll(a[i]));
    return static_cast<std::size_t>(result);
}
__attribute__((target("avx2,popcnt"))) inline std::size_t bitset_intersection_words_avx2(const std::uint64_t* a,const std::uint64_t* b,std::size_t n) noexcept {
    const auto table=_mm256_setr_epi8(0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4,0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4);
    const auto mask=_mm256_set1_epi8(15),zero=_mm256_setzero_si256();auto total=zero;std::size_t i=0;
    for(;n-i>=4;i+=4){const auto x=_mm256_and_si256(_mm256_loadu_si256(reinterpret_cast<const __m256i*>(a+i)),_mm256_loadu_si256(reinterpret_cast<const __m256i*>(b+i)));const auto lo=_mm256_shuffle_epi8(table,_mm256_and_si256(x,mask));const auto hi=_mm256_shuffle_epi8(table,_mm256_and_si256(_mm256_srli_epi16(x,4),mask));total=_mm256_add_epi64(total,_mm256_sad_epu8(_mm256_add_epi8(lo,hi),zero));}
    alignas(32) std::uint64_t lanes[4];_mm256_store_si256(reinterpret_cast<__m256i*>(lanes),total);auto result=lanes[0]+lanes[1]+lanes[2]+lanes[3];
    for(;i<n;++i)result+=static_cast<unsigned>(__builtin_popcountll(a[i]&b[i]));
    return static_cast<std::size_t>(result);
}

__attribute__((target("avx2,popcnt"), noinline)) inline std::size_t bitset_parity_words_avx2(const std::uint64_t* a,const std::uint64_t* b,std::size_t n)noexcept {
    auto total=_mm256_setzero_si256();std::size_t i=0;
    for(;n-i>=4;i+=4)total=_mm256_xor_si256(total,_mm256_and_si256(_mm256_loadu_si256(reinterpret_cast<const __m256i*>(a+i)),_mm256_loadu_si256(reinterpret_cast<const __m256i*>(b+i))));
    alignas(32)std::uint64_t lanes[4];_mm256_store_si256(reinterpret_cast<__m256i*>(lanes),total);auto value=lanes[0]^lanes[1]^lanes[2]^lanes[3];
    for(;i<n;++i)value^=a[i]&b[i];
    return static_cast<unsigned>(__builtin_popcountll(value))&1;
}

inline unsigned bitset_cpu_features() noexcept {
    static const unsigned features = (__builtin_cpu_supports("popcnt") ? 1U : 0U) | (__builtin_cpu_supports("avx2") ? 2U : 0U);
    return features;
}
#endif
inline std::size_t bitset_count_words(const std::uint64_t* words, std::size_t count) noexcept {
#if !defined(SIRKIT_DISABLE_SIMD) && (defined(__x86_64__) || defined(__i386__)) && (defined(__GNUC__) || defined(__clang__))
#if !(defined(__clang__) && defined(__AVX2__))
    if (count >= 4) {
        const auto features = bitset_cpu_features();
        if (count >= 64 && features == 3) return bitset_count_words_avx2(words, count);
        if (features & 1) return bitset_count_words_popcnt(words, count);
    }
#endif
#endif
    return bitset_count_words_scalar(words, count);
}
inline std::size_t bitset_intersection_words(const std::uint64_t* a, const std::uint64_t* b, std::size_t count) noexcept {
#if !defined(SIRKIT_DISABLE_SIMD) && (defined(__x86_64__) || defined(__i386__)) && (defined(__GNUC__) || defined(__clang__))
#if !(defined(__clang__) && defined(__AVX2__))
    if (count >= 4) {
        const auto features = bitset_cpu_features();
        if (count >= 64 && features == 3) return bitset_intersection_words_avx2(a, b, count);
        if (features & 1) return bitset_intersection_words_popcnt(a, b, count);
    }
#endif
#endif
    return bitset_intersection_words_scalar(a, b, count);
}
inline bool bitset_intersection_parity_words(const std::uint64_t* a, const std::uint64_t* b, std::size_t count) noexcept {
#if !defined(SIRKIT_DISABLE_SIMD) && (defined(__x86_64__) || defined(__i386__)) && (defined(__GNUC__) || defined(__clang__))
#if !(defined(__clang__) && defined(__AVX2__))
    if (count >= 64 && bitset_cpu_features() == 3) return bitset_parity_words_avx2(a, b, count) != 0;
#endif
#endif
    return bitset_intersection_parity_words_scalar(a, b, count);
}
}
#endif


} // namespace sirkit
// SIRKIT_NAMESPACE_CLOSE_V1
#include <optional>

// SIRKIT_NAMESPACE_OPEN_V1
namespace sirkit {

#ifndef SIRKIT_BINARY_MATRIX_DEFINED
#define SIRKIT_BINARY_MATRIX_DEFINED
class BinaryMatrix {
public:
    struct LinearSolution;
private:
    std::size_t rows_ = 0, cols_ = 0, stride_ = 0;
    std::vector<std::uint64_t> data_;
    static std::size_t stride_for(std::size_t cols) noexcept { return cols / 64 + (cols % 64 != 0); }
    static std::size_t storage_size(std::size_t rows, std::size_t stride) {
        const auto limit = std::vector<std::uint64_t>().max_size();
        if (stride && rows > limit / stride) throw std::length_error("BinaryMatrix capacity");
        return rows * stride;
    }
    void check_row(std::size_t row) const {
#ifndef SKIP_RUNTIME_CHECKS
        if (row >= rows_) throw std::out_of_range("BinaryMatrix row");
#else
        (void)row;
#endif
    }
    void check_position(std::size_t row, std::size_t col) const {
#ifndef SKIP_RUNTIME_CHECKS
        if (row >= rows_ || col >= cols_) throw std::out_of_range("BinaryMatrix position");
#else
        (void)row; (void)col;
#endif
    }
    void check_same_shape(const BinaryMatrix& other) const {
#ifndef SKIP_RUNTIME_CHECKS
        if (rows_ != other.rows_ || cols_ != other.cols_) throw std::invalid_argument("BinaryMatrix shape");
#else
        (void)other;
#endif
    }
    void check_square() const {
#ifndef SKIP_RUNTIME_CHECKS
        if (rows_ != cols_) throw std::invalid_argument("BinaryMatrix square");
#endif
    }
    void xor_suffix(std::size_t target, std::size_t source, std::size_t first_word) noexcept {
        const auto t = target * stride_, s = source * stride_;
        for (std::size_t word = first_word; word < stride_; ++word) data_[t + word] ^= data_[s + word];
    }
    static std::size_t eliminate(BinaryMatrix& work, BinaryMatrix* companion,
                                             std::vector<std::uint8_t>* rhs, bool reduced, std::vector<std::size_t>* pivots = nullptr) {
        if (pivots) pivots->reserve(std::min(work.rows_, work.cols_));
        if (!work.rows_ || !work.cols_) return 0;
        std::size_t rank = 0;
        for (std::size_t col = 0; col < work.cols_ && rank < work.rows_; ++col) {
            const auto word = col / 64, mask = std::uint64_t{1} << (col % 64);
            auto pivot = rank;
            while (pivot < work.rows_ && !(work.data_[pivot * work.stride_ + word] & mask)) ++pivot;
            if (pivot == work.rows_) continue;
            work.swap_rows(rank, pivot);
            if (companion) companion->swap_rows(rank, pivot);
            if (rhs) std::swap((*rhs)[rank], (*rhs)[pivot]);
            const auto first = reduced ? std::size_t{0} : rank + 1;
            for (auto row = first; row < work.rows_; ++row) if (row != rank && (work.data_[row * work.stride_ + word] & mask)) {
                // pivot行のそれ以前の列は0なのでword途中からでも既存pivotを壊さない。
                work.xor_suffix(row, rank, word);
                if (companion) companion->xor_suffix(row, rank, 0);
                if (rhs) (*rhs)[row] ^= (*rhs)[rank];
            }
            if (pivots) pivots->push_back(col);
            ++rank;
        }
        return rank;
    }
public:
    explicit BinaryMatrix(std::size_t rows = 0, std::size_t cols = 0)
        : rows_(rows), cols_(cols), stride_(stride_for(cols)), data_(storage_size(rows, stride_)) {}
    BinaryMatrix(const BinaryMatrix&) = default;
    BinaryMatrix& operator=(const BinaryMatrix& other) { if (this != &other) { BinaryMatrix copy(other); swap(copy); } return *this; }
    BinaryMatrix(BinaryMatrix&& other) noexcept { swap(other); }
    BinaryMatrix& operator=(BinaryMatrix&& other) noexcept { if (this != &other) { clear(); swap(other); } return *this; }
    void swap(BinaryMatrix& other) noexcept { std::swap(rows_, other.rows_); std::swap(cols_, other.cols_); std::swap(stride_, other.stride_); data_.swap(other.data_); }
    friend void swap(BinaryMatrix& a, BinaryMatrix& b) noexcept { a.swap(b); }
    std::size_t rows() const noexcept { return rows_; }
    std::size_t cols() const noexcept { return cols_; }
    bool empty() const noexcept { return !rows_ || !cols_; }
    std::span<const std::uint64_t> row_words(std::size_t row) const {
        check_row(row); if (!stride_) return {};
        return std::span<const std::uint64_t>(data_).subspan(row * stride_, stride_);
    }
    bool test(std::size_t row, std::size_t col) const { check_position(row, col); return ((data_[row * stride_ + col / 64] >> (col % 64)) & 1) != 0; }
    bool operator()(std::size_t row, std::size_t col) const { return test(row, col); }
    BinaryMatrix& set(std::size_t row, std::size_t col, bool value = true) {
        check_position(row, col); auto& word = data_[row * stride_ + col / 64]; const auto mask = std::uint64_t{1} << (col % 64);
        if (value) word |= mask; else word &= ~mask; return *this;
    }
    BinaryMatrix& flip(std::size_t row, std::size_t col) { check_position(row, col); data_[row * stride_ + col / 64] ^= std::uint64_t{1} << (col % 64); return *this; }
    void swap_rows(std::size_t a, std::size_t b) {
        check_row(a); check_row(b); if (a == b) return;
        for (std::size_t word = 0; word < stride_; ++word) std::swap(data_[a * stride_ + word], data_[b * stride_ + word]);
    }
    void xor_rows(std::size_t target, std::size_t source, std::size_t first_col = 0) {
        check_row(target); check_row(source);
#ifndef SKIP_RUNTIME_CHECKS
        if (first_col > cols_) throw std::out_of_range("BinaryMatrix first column");
#endif
        if (first_col == cols_) return;
        const auto first_word = first_col / 64;
        data_[target * stride_ + first_word] ^= data_[source * stride_ + first_word] & (~std::uint64_t{0} << (first_col % 64));
        xor_suffix(target, source, first_word + 1);
    }
    static BinaryMatrix identity(std::size_t n) { BinaryMatrix result(n, n); for (std::size_t i = 0; i < n; ++i) result.data_[i * result.stride_ + i / 64] |= std::uint64_t{1} << (i % 64); return result; }
    BinaryMatrix transpose() const {
        BinaryMatrix result(cols_, rows_); if (empty()) return result;
        for (std::size_t row = 0; row < rows_; ++row) for (std::size_t col = 0; col < cols_; ++col)
            if ((data_[row * stride_ + col / 64] >> (col % 64)) & 1) result.data_[col * result.stride_ + row / 64] |= std::uint64_t{1} << (row % 64);
        return result;
    }
    BinaryMatrix multiply(const BinaryMatrix& other) const {
#ifndef SKIP_RUNTIME_CHECKS
        if (cols_ != other.rows_) throw std::invalid_argument("BinaryMatrix product shape");
#endif
        BinaryMatrix result(rows_, other.cols_); if (!rows_ || !cols_ || !other.cols_) return result;
        const auto transposed = other.transpose();
        for (std::size_t row = 0; row < rows_; ++row) for (std::size_t col = 0; col < other.cols_; ++col)
            if (/*SIRKIT_NS_REWRITE_V1:R:cmVpbnNpcms6OmRldGFpbA==*/::sirkit::detail/*SIRKIT_NS_REWRITE_END_V1*/::bitset_intersection_parity_words(data_.data() + row * stride_, transposed.data_.data() + col * transposed.stride_, stride_))
                result.data_[row * result.stride_ + col / 64] |= std::uint64_t{1} << (col % 64);
        return result;
    }
    BinaryMatrix operator*(const BinaryMatrix& other) const { return multiply(other); }
    BinaryMatrix& operator*=(const BinaryMatrix& other) { auto result = multiply(other); swap(result); return *this; }
    BinaryMatrix& operator+=(const BinaryMatrix& other) { check_same_shape(other); for (std::size_t i = 0; i < data_.size(); ++i) data_[i] ^= other.data_[i]; return *this; }
    BinaryMatrix& operator^=(const BinaryMatrix& other) { return *this += other; }
    friend BinaryMatrix operator+(BinaryMatrix a, const BinaryMatrix& b) { a += b; return a; }
    friend BinaryMatrix operator^(BinaryMatrix a, const BinaryMatrix& b) { a ^= b; return a; }
    bool operator==(const BinaryMatrix& other) const noexcept { return rows_ == other.rows_ && cols_ == other.cols_ && data_ == other.data_; }
    BinaryMatrix pow(std::uint64_t exponent) const {
        check_square(); auto result = identity(rows_); if (!exponent || !rows_) return result;
        auto base = *this;
        while (exponent) { if (exponent & 1) result *= base; exponent >>= 1; if (exponent) base *= base; }
        return result;
    }
    std::size_t rank() const { auto work = *this; return eliminate(work, nullptr, nullptr, false); }
    bool determinant() const { check_square(); return rank() == rows_; }
    std::optional<BinaryMatrix> inverse() const {
        check_square(); auto work = *this, result = identity(rows_);
        if (eliminate(work, &result, nullptr, true) != rows_) return std::nullopt;
        return result;
    }
    std::optional<LinearSolution> solve(std::span<const std::uint8_t> rhs) const;
    void reset(std::size_t rows = 0, std::size_t cols = 0) { BinaryMatrix next(rows, cols); swap(next); }
    void clear() noexcept { data_.clear(); rows_ = cols_ = stride_ = 0; }
};

struct BinaryMatrix::LinearSolution {
    std::vector<std::uint8_t> particular;
    BinaryMatrix kernel;
    std::vector<std::size_t> pivot_columns;
    LinearSolution() = default;
    LinearSolution(std::vector<std::uint8_t> value, BinaryMatrix basis, std::vector<std::size_t> pivots)
        : particular(std::move(value)), kernel(std::move(basis)), pivot_columns(std::move(pivots)) {}
    LinearSolution(const LinearSolution&) = default;
    LinearSolution& operator=(const LinearSolution& other) { if (this != &other) { LinearSolution copy(other); swap(copy); } return *this; }
    LinearSolution(LinearSolution&& other) noexcept { swap(other); }
    LinearSolution& operator=(LinearSolution&& other) noexcept {
        if (this != &other) { particular.clear(); kernel.clear(); pivot_columns.clear(); swap(other); } return *this;
    }
    void swap(LinearSolution& other) noexcept { particular.swap(other.particular); kernel.swap(other.kernel); pivot_columns.swap(other.pivot_columns); }
    friend void swap(LinearSolution& a, LinearSolution& b) noexcept { a.swap(b); }
};

inline std::optional<BinaryMatrix::LinearSolution> BinaryMatrix::solve(std::span<const std::uint8_t> rhs) const {
#ifndef SKIP_RUNTIME_CHECKS
    if (rhs.size() != rows_) throw std::invalid_argument("BinaryMatrix rhs length");
#endif
    if (!cols_) {
        for (std::size_t row = 0; row < rows_; ++row) {
#ifndef SKIP_RUNTIME_CHECKS
            if (rhs[row] > 1) throw std::invalid_argument("BinaryMatrix rhs bit");
#endif
            if (rhs[row]) return std::nullopt;
        }
        return LinearSolution{};
    }
    std::vector<std::uint8_t> values(rows_);
    for (std::size_t i = 0; i < rows_; ++i) {
#ifndef SKIP_RUNTIME_CHECKS
        if (rhs[i] > 1) throw std::invalid_argument("BinaryMatrix rhs bit");
#endif
        values[i] = rhs[i];
    }
    auto work = *this; std::vector<std::size_t> pivots; const auto rank = eliminate(work, nullptr, &values, true, &pivots);
    for (auto row = rank; row < rows_; ++row) if (values[row]) return std::nullopt;
    LinearSolution result{std::vector<std::uint8_t>(cols_), BinaryMatrix(cols_ - rank, cols_), std::move(pivots)};
    for (std::size_t row = 0; row < rank; ++row) result.particular[result.pivot_columns[row]] = values[row];
    std::size_t pivot = 0, basis = 0;
    for (std::size_t col = 0; col < cols_; ++col) {
        if (pivot < rank && result.pivot_columns[pivot] == col) { ++pivot; continue; }
        result.kernel.set(basis, col);
        for (std::size_t row = 0; row < rank; ++row) if (work.test(row, col)) result.kernel.set(basis, result.pivot_columns[row]);
        ++basis;
    }
    return result;
}
#endif

} // namespace sirkit
// SIRKIT_NAMESPACE_CLOSE_V1
// SIRKIT_NAMESPACE_END_V1
Back to top page