競技プログラミング用 C++ ライブラリ
components/matrix_arithmetic.hpp · GitHub で見る
共通ページ
math/matrix.hpp が使う連続配列の行列積・消去処理です。通常は公開側の Matrix<T> を使います。体の演算・内積・配列の定数倍と加算は 体の内部演算 と共有しています。
| 操作 | 内容 | 計算量 |
|---|---|---|
matrix_detail::integer_determinant(a,n) |
符号付き整数の正方行列式を Bareiss 法で求める | \(O(n^3)\) |
matrix_detail::multiply(a,b,n,k,m) |
平坦な配列の \(n\times k\) と \(k\times m\) を掛ける | \(O(nkm)\) |
matrix_detail::field(a,f) |
要素型に応じて内部表現へ変換し、f.template operator()<Ops>(work) を呼ぶ。結果を元の配列に戻す |
要素数に比例+f の処理時間 |
matrix_detail::eliminate<Ops>(a,h,stride,columns,reduced,eps) |
先頭 columns 列を対象に消去。ピボット列と、交換の符号を含むピボットの積を返す |
\(O(h\cdot\mathrm{stride}\cdot\min(h,\mathrm{columns}))\) |
Ops::add(a,b) / Ops::mul(a,b) / Ops::neg(a) / Ops::inv(a)
|
内部表現での体の演算 | \(O(1)\) |
Ops::zero(a,eps) / Ops::better(a,b)
|
0 判定/ピボットの比較 | \(O(1)\) |
Ops::scale(a,n,x) / Ops::axpy(a,b,n,x)
|
連続領域の定数倍/a += x*b
|
\(O(n)\) |
Field<T> は通常の体の演算、ModularField<T> は固定法の modint を標準表現の uint32_t に変換して扱います。後者の AVX2・AVX512 処理は対応する CPU でのみ呼びます。
行列積は対応 CPU で AVX512 を使い、非対応なら AVX2 または通常処理を使います。剰余は整数で補正するため、浮動小数点の近似商を使う経路でも結果は厳密です。MATRIX_DISABLE_AVX2 を定義すると両方の SIMD 経路を無効にできます。
整数の行列式は時間 \(O(n^3)\)、追加空間 \(O(n^2)\)。行列積は時間 \(O(nkm)\)、追加空間 \(O(nk+km+nm)\)。消去は時間 \(O(h\cdot\mathrm{stride}\cdot\min(h,\mathrm{columns}))\)、ピボット列の空間は \(O(\min(h,\mathrm{columns}))\)。配列の変換は時間・追加空間ともに要素数に比例し、行の定数倍・加算は時間 \(O(n)\)、追加空間 \(O(1)\) です。要素の演算・コピーを \(O(1)\) とします。
#ifndef MATRIX_ARITHMETIC_HPP
#define MATRIX_ARITHMETIC_HPP
#include "matrix_base_arithmetic.hpp"
#include "field_arithmetic.hpp"
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <type_traits>
#include <utility>
#include <vector>
#if defined(__x86_64__) || defined(__i386__)
#include <immintrin.h>
#endif
namespace matrix_detail {
using field_detail::SmallModint, field_detail::small_modint, field_detail::avx2, field_detail::ModularField;
template <class T, class F>
auto field(std::vector<T> &a, F &&f) {
static_assert(!integer<T>);
if constexpr (small_modint<T>) {
std::vector<std::uint32_t> work(a.size());
for (std::size_t i = 0; i < a.size(); ++i) work[i] = a[i].val();
auto result = f.template operator()<ModularField<T>>(work);
for (std::size_t i = 0; i < a.size(); ++i) a[i] = T::raw(work[i]);
return result;
} else return f.template operator()<Field<T>>(a);
}
#if defined(__GNUC__) && !defined(__clang__) && (defined(__x86_64__) || defined(__i386__))
#pragma GCC push_options
#pragma GCC optimize("O3")
#endif
template <std::uint32_t mod>
void product_scalar(const std::uint32_t *a, const std::uint32_t *b, std::uint32_t *c, int n, int inner, int m) {
constexpr int step = mod <= (std::uint32_t(1) << 30) ? 16 : 4;
for (int i = 0; i < n; ++i) for (int j = 0; j < m; j += 32) {
int width = std::min(32, m - j);
for (int k = 0; k < inner; k += step) {
std::uint64_t sums[32]{};
for (int t = k; t < std::min(inner, k + step); ++t) {
std::uint64_t x = a[std::size_t(i) * inner + t];
const auto *row = b + std::size_t(t) * m + j;
for (int s = 0; s < width; ++s) sums[s] += x * row[s];
}
for (int s = 0; s < width; ++s) c[std::size_t(i) * m + j + s] = (sums[s] + c[std::size_t(i) * m + j + s]) % mod;
}
}
}
#if (defined(__x86_64__) || defined(__i386__)) && (defined(__GNUC__) || defined(__clang__))
inline bool avx512_product() {
static const bool supported = __builtin_cpu_supports("avx512f") && __builtin_cpu_supports("avx512dq");
return avx2() && supported;
}
template <std::uint32_t mod>
__attribute__((target("avx512f,avx512dq"))) __m512i reduce_product_avx512(__m512i sum) {
const auto p = _mm512_set1_epi64(mod);
const auto q = _mm512_cvt_roundpd_epi64(
_mm512_mul_pd(_mm512_cvtepi64_pd(sum), _mm512_set1_pd(1.0 / mod)),
_MM_FROUND_TO_NEG_INF | _MM_FROUND_NO_EXC);
auto r = _mm512_sub_epi64(sum, _mm512_mullo_epi64(q, p));
r = _mm512_mask_add_epi64(r, _mm512_cmp_epi64_mask(r, _mm512_setzero_si512(), _MM_CMPINT_LT), r, p);
return _mm512_mask_sub_epi64(r, _mm512_cmp_epi64_mask(r, p, _MM_CMPINT_NLT), r, p);
}
template <std::uint32_t mod, int rows = 8>
__attribute__((target("avx512f,avx512dq"))) void product_packed_avx512(const std::int32_t *a, const std::int32_t *b, std::uint32_t *c, int n, int inner, int m) {
constexpr std::int64_t radius = mod / 2;
constexpr std::int64_t residue = (std::uint64_t(1) << 32) % mod;
constexpr std::int64_t folded_bound = (std::int64_t(1) << 31) * residue + 0xffffffffu;
constexpr int step = int(std::min<std::int64_t>(32, (std::numeric_limits<std::int64_t>::max() - folded_bound) / (radius * radius)));
int i = 0;
for (; i + rows <= n; i += rows) {
for (int j = 0; j < m; j += 16) {
const int width = std::min(16, m - j);
const __mmask16 active = (1u << width) - 1;
__m512i sums[rows][2];
for (int r = 0; r < rows; ++r) {
auto previous = _mm512_maskz_loadu_epi32(active, c + std::size_t(i + r) * m + j);
sums[r][0] = _mm512_and_si512(previous, _mm512_set1_epi64(0xffffffffu));
sums[r][1] = _mm512_srli_epi64(previous, 32);
}
for (int k = 0; k < inner; k += step) {
for (int t = k; t < std::min(inner, k + step); ++t) {
auto x = _mm512_maskz_loadu_epi32(active, b + std::size_t(j) * inner + std::size_t(t) * width);
auto y = _mm512_srli_epi64(x, 32);
for (int r = 0; r < rows; ++r) {
auto z = _mm512_set1_epi32(a[std::size_t(i + r) * inner + t]);
sums[r][0] = _mm512_add_epi64(sums[r][0], _mm512_mul_epi32(x, z));
sums[r][1] = _mm512_add_epi64(sums[r][1], _mm512_mul_epi32(y, z));
}
}
for (int r = 0; r < rows; ++r) for (int q = 0; q < 2; ++q) {
auto x = sums[r][q];
sums[r][q] = _mm512_add_epi64(_mm512_mul_epi32(_mm512_srli_epi64(x, 32), _mm512_set1_epi32(residue)), _mm512_and_si512(x, _mm512_set1_epi64(0xffffffffu)));
}
}
for (int r = 0; r < rows; ++r) {
auto even = reduce_product_avx512<mod>(sums[r][0]), odd = reduce_product_avx512<mod>(sums[r][1]);
_mm512_mask_storeu_epi32(c + std::size_t(i + r) * m + j, active, _mm512_or_si512(even, _mm512_slli_epi64(odd, 32)));
}
}
}
if constexpr (rows > 1) {
if (i < n) product_packed_avx512<mod, rows / 2>(a + std::size_t(i) * inner, b, c + std::size_t(i) * m, n - i, inner, m);
}
}
template <std::uint32_t mod, int rows = 4>
__attribute__((target("avx2"))) void product_packed_avx2(const std::int32_t *a, const std::int32_t *b, std::uint32_t *c, int n, int inner, int m) {
constexpr std::int64_t radius = mod / 2;
constexpr std::int64_t residue = (std::uint64_t(1) << 32) % mod;
constexpr std::int64_t folded_bound = (std::int64_t(1) << 31) * residue + 0xffffffffu;
constexpr int step = int(std::min<std::int64_t>(32, (std::numeric_limits<std::int64_t>::max() - folded_bound) / (radius * radius)));
auto reduce = [](std::int64_t sum) {
std::int64_t r = sum % std::int64_t(mod);
return std::uint32_t(r < 0 ? r + mod : r);
};
int i = 0;
for (; i + rows <= n; i += rows) {
for (int j = 0; j < m; j += 8) {
int width = std::min(8, m - j);
auto active = _mm256_cmpgt_epi32(_mm256_set1_epi32(width), _mm256_setr_epi32(0, 1, 2, 3, 4, 5, 6, 7));
__m256i sums[rows][2];
for (int r = 0; r < rows; ++r) {
auto previous = _mm256_maskload_epi32(reinterpret_cast<const int *>(c + std::size_t(i + r) * m + j), active);
sums[r][0] = _mm256_and_si256(previous, _mm256_set1_epi64x(0xffffffffu));
sums[r][1] = _mm256_srli_epi64(previous, 32);
}
for (int k = 0; k < inner; k += step) {
for (int t = k; t < std::min(inner, k + step); ++t) {
auto x = _mm256_maskload_epi32(b + std::size_t(j) * inner + std::size_t(t) * width, active);
auto y = _mm256_srli_epi64(x, 32);
for (int r = 0; r < rows; ++r) {
auto z = _mm256_set1_epi32(a[std::size_t(i + r) * inner + t]);
sums[r][0] = _mm256_add_epi64(sums[r][0], _mm256_mul_epi32(x, z));
sums[r][1] = _mm256_add_epi64(sums[r][1], _mm256_mul_epi32(y, z));
}
}
for (int r = 0; r < rows; ++r) for (int q = 0; q < 2; ++q) {
auto x = sums[r][q];
sums[r][q] = _mm256_add_epi64(_mm256_mul_epi32(_mm256_srli_epi64(x, 32), _mm256_set1_epi32(residue)), _mm256_and_si256(x, _mm256_set1_epi64x(0xffffffffu)));
}
}
for (int r = 0; r < rows; ++r) {
std::int64_t even[4], odd[4];
_mm256_storeu_si256(reinterpret_cast<__m256i *>(even), sums[r][0]);
_mm256_storeu_si256(reinterpret_cast<__m256i *>(odd), sums[r][1]);
std::uint32_t result[8];
for (int q = 0; q < 4; ++q) result[q * 2] = reduce(even[q]), result[q * 2 + 1] = reduce(odd[q]);
_mm256_maskstore_epi32(reinterpret_cast<int *>(c + std::size_t(i + r) * m + j), active, _mm256_loadu_si256(reinterpret_cast<const __m256i *>(result)));
}
}
}
if constexpr (rows == 4) {
if (i < n) product_packed_avx2<mod, 1>(a + std::size_t(i) * inner, b, c + std::size_t(i) * m, n - i, inner, m);
}
}
#endif
template <class T>
std::vector<T> multiply(const std::vector<T> &a, const std::vector<T> &b, int n, int inner, int m) {
std::vector<T> c(std::size_t(n) * m, T(0));
if (!n || !inner || !m) return c;
auto basic = [&] {
for (int i = 0; i < n; ++i) for (int k = 0; k < inner; ++k) {
const T &x = a[std::size_t(i) * inner + k];
for (int j = 0; j < m; ++j) c[std::size_t(i) * m + j] += x * b[std::size_t(k) * m + j];
}
};
if constexpr (small_modint<T>) {
if (std::uint64_t(n) * m <= 128u / unsigned(inner)) { basic(); return c; }
#if (defined(__x86_64__) || defined(__i386__)) && (defined(__GNUC__) || defined(__clang__))
if (inner >= 16 && m >= 8 && avx2()) {
const int block = avx512_product() ? 16 : 8;
std::vector<std::int32_t> x(a.size()), y(b.size());
std::vector<std::uint32_t> z(c.size());
auto center = [](std::uint32_t value) {
std::int32_t v = value;
return v <= std::int32_t((T::mod() - 1) / 2) ? v : v - std::int32_t(T::mod());
};
for (std::size_t i = 0; i < a.size(); ++i) x[i] = center(a[i].val());
for (int j = 0; j < m; j += block) {
int width = std::min(block, m - j);
for (int k = 0; k < inner; ++k) for (int s = 0; s < width; ++s)
y[std::size_t(j) * inner + std::size_t(k) * width + s] = center(b[std::size_t(k) * m + j + s].val());
}
if (block == 16) product_packed_avx512<T::mod()>(x.data(), y.data(), z.data(), n, inner, m);
else product_packed_avx2<T::mod()>(x.data(), y.data(), z.data(), n, inner, m);
for (std::size_t i = 0; i < c.size(); ++i) c[i] = T::raw(z[i]);
return c;
}
#endif
std::vector<std::uint32_t> x(a.size()), y(b.size()), z(c.size());
for (std::size_t i = 0; i < a.size(); ++i) x[i] = a[i].val();
for (std::size_t i = 0; i < b.size(); ++i) y[i] = b[i].val();
product_scalar<T::mod()>(x.data(), y.data(), z.data(), n, inner, m);
for (std::size_t i = 0; i < c.size(); ++i) c[i] = T::raw(z[i]);
} else basic();
return c;
}
#if defined(__GNUC__) && !defined(__clang__) && (defined(__x86_64__) || defined(__i386__))
#pragma GCC pop_options
#endif
}
#endif
#line 1 "components/matrix_arithmetic.hpp"
#line 1 "components/matrix_base_arithmetic.hpp"
#line 1 "components/field_base.hpp"
#include <cmath>
#include <type_traits>
namespace field_detail {
template <class T>
struct Field {
using V = T;
static T add(T a, T b) { return a + b; }
static T mul(T a, T b) { return a * b; }
static T neg(T a) { return -a; }
static T inv(T a) { return T(1) / a; }
static bool zero(T a, long double eps) {
if constexpr (std::is_floating_point_v<T>) return std::abs(a) <= eps;
else { (void)eps; return a == T(0); }
}
static bool better(T a, T b) {
if constexpr (std::is_floating_point_v<T>) return std::abs(a) > std::abs(b);
else { (void)a; (void)b; return false; }
}
static T dot(const T *a, const T *b, int n) {
T result = 0;
for (int i = 0; i < n; ++i) result += a[i] * b[i];
return result;
}
static void scale(T *a, int n, T x) { for (int i = 0; i < n; ++i) a[i] *= x; }
static void axpy(T *a, const T *b, int n, T x) { for (int i = 0; i < n; ++i) a[i] += x * b[i]; }
};
}
#line 5 "components/matrix_base_arithmetic.hpp"
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <limits>
#line 11 "components/matrix_base_arithmetic.hpp"
#include <utility>
#include <vector>
namespace matrix_detail {
template <class T>
inline constexpr bool integer = std::is_integral_v<T> || std::is_same_v<T, __int128_t> || std::is_same_v<T, __uint128_t>;
using field_detail::Field;
template <class Ops>
struct Elimination {
std::vector<int> pivots;
typename Ops::V determinant = 1;
};
template <class Ops, bool exact = false>
Elimination<Ops> eliminate(std::vector<typename Ops::V> &a, int h, int stride, int columns, bool reduced, long double eps) {
using V = typename Ops::V;
Elimination<Ops> result;
result.pivots.reserve(std::min(h, columns));
int rank = 0;
for (int col = 0; col < columns && rank < h; ++col) {
int p = -1;
for (int i = rank; i < h; ++i) {
V x = a[std::size_t(i) * stride + col];
if (!Ops::zero(x, eps) && (p < 0 || Ops::better(x, a[std::size_t(p) * stride + col]))) p = i;
}
if (p < 0) continue;
V *row = a.data() + std::size_t(rank) * stride;
if (p != rank) {
std::swap_ranges(row, row + stride, a.data() + std::size_t(p) * stride);
result.determinant = Ops::neg(result.determinant);
}
result.determinant = Ops::mul(result.determinant, row[col]);
Ops::scale(row + col + 1, stride - col - 1, Ops::inv(row[col]));
row[col] = V(1);
for (int i = rank + 1; i < h; ++i) {
V *dst = a.data() + std::size_t(i) * stride;
V x = dst[col];
if (!Ops::zero(x, eps)) Ops::axpy(dst + col + 1, row + col + 1, stride - col - 1, Ops::neg(x));
dst[col] = V(0);
}
result.pivots.push_back(col);
++rank;
}
bool full = exact && rank == columns;
if (reduced) for (int k = rank - 1; k >= 0; --k) {
int col = result.pivots[k], start = full ? columns : col + 1;
const V *row = a.data() + std::size_t(k) * stride;
for (int i = 0; i < k; ++i) {
V *dst = a.data() + std::size_t(i) * stride;
V x = dst[col];
if (!Ops::zero(x, eps) && (!full || start < stride)) Ops::axpy(dst + start, row + start, stride - start, Ops::neg(x));
dst[col] = V(0);
}
}
return result;
}
template <class T>
[[gnu::noinline]] T integer_determinant(const std::vector<T> &a, int n) {
static_assert(std::numeric_limits<T>::is_signed);
using W = __int128_t;
std::vector<W> work(a.begin(), a.end());
W previous = 1, sign = 1;
if (!n) return T(1);
for (int k = 0; k + 1 < n; ++k) {
int pivot = k;
while (pivot < n && work[std::size_t(pivot) * n + k] == 0) ++pivot;
if (pivot == n) return T(0);
if (pivot != k) { for (int j = 0; j < n; ++j) std::swap(work[std::size_t(k) * n + j], work[std::size_t(pivot) * n + j]); sign = -sign; }
W p = work[std::size_t(k) * n + k];
for (int i = k + 1; i < n; ++i) {
for (int j = k + 1; j < n; ++j) {
W value = work[std::size_t(i) * n + j] * p - work[std::size_t(i) * n + k] * work[std::size_t(k) * n + j];
assert(value % previous == 0);
work[std::size_t(i) * n + j] = value / previous;
}
work[std::size_t(i) * n + k] = 0;
}
previous = p;
}
W result = sign * work.back();
assert(result >= std::numeric_limits<T>::lowest() && result <= std::numeric_limits<T>::max());
return T(result);
}
template <class T>
std::vector<T> basic_multiply(const std::vector<T> &a, const std::vector<T> &b, int n, int inner, int m) {
std::vector<T> c(std::size_t(n) * m, T(0));
for (int i = 0; i < n; ++i) for (int k = 0; k < inner; ++k) {
const T &x = a[std::size_t(i) * inner + k];
for (int j = 0; j < m; ++j) c[std::size_t(i) * m + j] += x * b[std::size_t(k) * m + j];
}
return c;
}
}
#line 1 "components/field_arithmetic.hpp"
#line 9 "components/field_arithmetic.hpp"
#if (defined(__x86_64__) || defined(__i386__)) && (defined(__GNUC__) || defined(__clang__))
#include <immintrin.h>
#endif
namespace field_detail {
template <class T, class = void>
struct SmallModint : std::false_type {};
template <class T>
struct SmallModint<T, std::void_t<decltype(std::integral_constant<std::uint32_t, T::mod()>{}),
decltype(std::declval<T>().val()), decltype(T::raw(std::uint32_t{}))>>
: std::bool_constant<(T::mod() > 1 && T::mod() < (std::uint32_t(1) << 31))
&& std::is_convertible_v<decltype(std::declval<T>().val()), std::uint32_t>
&& std::is_same_v<decltype(T::raw(std::uint32_t{})), T>> {};
template <class T>
inline constexpr bool small_modint = SmallModint<T>::value;
inline bool avx2() {
#if (defined(__x86_64__) || defined(__i386__)) && (defined(__GNUC__) || defined(__clang__)) && !defined(FIELD_DISABLE_AVX2) && !defined(MATRIX_DISABLE_AVX2)
static const bool enabled = __builtin_cpu_supports("avx2");
return enabled;
#else
return false;
#endif
}
template <class T>
struct ModularField {
using V = std::uint32_t;
static constexpr V mod = T::mod();
static V add(V a, V b) { V c = a + b; return c < mod ? c : c - mod; }
static V mul(V a, V b) { return std::uint64_t(a) * b % mod; }
static V neg(V a) { return a ? mod - a : 0; }
static V dot(const V *a, const V *b, int n) {
constexpr int step = mod <= (V(1) << 30) ? 16 : 4;
std::uint64_t sum = 0;
for (int i = 0; i < n; i += step) {
for (int j = i; j < std::min(n, i + step); ++j) sum += std::uint64_t(a[j]) * b[j];
sum %= mod;
}
return sum;
}
static V inv(V a) { return (T(1) / T::raw(a)).val(); }
static bool zero(V a, long double) { return !a; }
static bool better(V, V) { return false; }
static V product(V a, V x, V q) {
V r = a * x - V((std::uint64_t(a) * q) >> 32) * mod;
return r < mod ? r : r - mod;
}
#if (defined(__x86_64__) || defined(__i386__)) && (defined(__GNUC__) || defined(__clang__))
__attribute__((target("avx2"))) static __m256i product8(__m256i a, __m256i x, __m256i q) {
__m256i p = _mm256_set1_epi32(mod);
__m256i even = _mm256_srli_epi64(_mm256_mul_epu32(a, q), 32);
__m256i odd = _mm256_mul_epu32(_mm256_srli_epi64(a, 32), q);
__m256i high = _mm256_or_si256(even, _mm256_slli_epi64(_mm256_srli_epi64(odd, 32), 32));
__m256i r = _mm256_sub_epi32(_mm256_mullo_epi32(a, x), _mm256_mullo_epi32(high, p));
return _mm256_min_epu32(r, _mm256_sub_epi32(r, p));
}
__attribute__((target("avx512f"))) static __m512i product16(__m512i a, __m512i x, __m512i q) {
const auto p = _mm512_set1_epi32(mod);
auto even = _mm512_srli_epi64(_mm512_mul_epu32(a, q), 32);
auto odd = _mm512_mul_epu32(_mm512_srli_epi64(a, 32), q);
auto high = _mm512_mask_blend_epi32(0xaaaa, even, odd);
auto r = _mm512_sub_epi32(_mm512_mullo_epi32(a, x), _mm512_mullo_epi32(high, p));
return _mm512_min_epu32(r, _mm512_sub_epi32(r, p));
}
template <bool add_to>
__attribute__((target("avx512f"))) static void apply16(V *a, const V *b, int n, V x, V q) {
const auto vx = _mm512_set1_epi32(x), vq = _mm512_set1_epi32(q), p = _mm512_set1_epi32(mod);
int i = 0;
for (; i + 16 <= n; i += 16) {
auto r = product16(_mm512_loadu_si512(b + i), vx, vq);
if constexpr (add_to) {
r = _mm512_add_epi32(r, _mm512_loadu_si512(a + i));
r = _mm512_min_epu32(r, _mm512_sub_epi32(r, p));
}
_mm512_storeu_si512(a + i, r);
}
for (; i < n; ++i) {
V r = product(b[i], x, q);
if constexpr (add_to) a[i] = add(a[i], r);
else a[i] = r;
}
}
template <bool add_to>
__attribute__((target("avx2"))) static void apply8(V *a, const V *b, int n, V x, V q) {
__m256i vx = _mm256_set1_epi32(x), vq = _mm256_set1_epi32(q), p = _mm256_set1_epi32(mod);
int i = 0;
for (; i + 8 <= n; i += 8) {
__m256i r = product8(_mm256_loadu_si256(reinterpret_cast<const __m256i *>(b + i)), vx, vq);
if constexpr (add_to) {
r = _mm256_add_epi32(r, _mm256_loadu_si256(reinterpret_cast<const __m256i *>(a + i)));
r = _mm256_min_epu32(r, _mm256_sub_epi32(r, p));
}
_mm256_storeu_si256(reinterpret_cast<__m256i *>(a + i), r);
}
for (; i < n; ++i) {
V r = product(b[i], x, q);
if constexpr (add_to) a[i] = add(a[i], r);
else a[i] = r;
}
}
#endif
template <bool add_to>
static void apply(V *a, const V *b, int n, V x) {
V q = (std::uint64_t(x) << 32) / mod;
#if (defined(__x86_64__) || defined(__i386__)) && (defined(__GNUC__) || defined(__clang__))
if (n >= 64 && avx2() && __builtin_cpu_supports("avx512f")) { apply16<add_to>(a, b, n, x, q); return; }
if (n >= 16 && avx2()) { apply8<add_to>(a, b, n, x, q); return; }
#endif
for (int i = 0; i < n; ++i) {
V r = product(b[i], x, q);
if constexpr (add_to) a[i] = add(a[i], r);
else a[i] = r;
}
}
static void scale(V *a, int n, V x) { apply<false>(a, a, n, x); }
static void axpy(V *a, const V *b, int n, V x) { apply<true>(a, b, n, x); }
};
}
#line 6 "components/matrix_arithmetic.hpp"
#line 15 "components/matrix_arithmetic.hpp"
#if defined(__x86_64__) || defined(__i386__)
#include <immintrin.h>
#endif
namespace matrix_detail {
using field_detail::SmallModint, field_detail::small_modint, field_detail::avx2, field_detail::ModularField;
template <class T, class F>
auto field(std::vector<T> &a, F &&f) {
static_assert(!integer<T>);
if constexpr (small_modint<T>) {
std::vector<std::uint32_t> work(a.size());
for (std::size_t i = 0; i < a.size(); ++i) work[i] = a[i].val();
auto result = f.template operator()<ModularField<T>>(work);
for (std::size_t i = 0; i < a.size(); ++i) a[i] = T::raw(work[i]);
return result;
} else return f.template operator()<Field<T>>(a);
}
#if defined(__GNUC__) && !defined(__clang__) && (defined(__x86_64__) || defined(__i386__))
#pragma GCC push_options
#pragma GCC optimize("O3")
#endif
template <std::uint32_t mod>
void product_scalar(const std::uint32_t *a, const std::uint32_t *b, std::uint32_t *c, int n, int inner, int m) {
constexpr int step = mod <= (std::uint32_t(1) << 30) ? 16 : 4;
for (int i = 0; i < n; ++i) for (int j = 0; j < m; j += 32) {
int width = std::min(32, m - j);
for (int k = 0; k < inner; k += step) {
std::uint64_t sums[32]{};
for (int t = k; t < std::min(inner, k + step); ++t) {
std::uint64_t x = a[std::size_t(i) * inner + t];
const auto *row = b + std::size_t(t) * m + j;
for (int s = 0; s < width; ++s) sums[s] += x * row[s];
}
for (int s = 0; s < width; ++s) c[std::size_t(i) * m + j + s] = (sums[s] + c[std::size_t(i) * m + j + s]) % mod;
}
}
}
#if (defined(__x86_64__) || defined(__i386__)) && (defined(__GNUC__) || defined(__clang__))
inline bool avx512_product() {
static const bool supported = __builtin_cpu_supports("avx512f") && __builtin_cpu_supports("avx512dq");
return avx2() && supported;
}
template <std::uint32_t mod>
__attribute__((target("avx512f,avx512dq"))) __m512i reduce_product_avx512(__m512i sum) {
const auto p = _mm512_set1_epi64(mod);
const auto q = _mm512_cvt_roundpd_epi64(
_mm512_mul_pd(_mm512_cvtepi64_pd(sum), _mm512_set1_pd(1.0 / mod)),
_MM_FROUND_TO_NEG_INF | _MM_FROUND_NO_EXC);
auto r = _mm512_sub_epi64(sum, _mm512_mullo_epi64(q, p));
r = _mm512_mask_add_epi64(r, _mm512_cmp_epi64_mask(r, _mm512_setzero_si512(), _MM_CMPINT_LT), r, p);
return _mm512_mask_sub_epi64(r, _mm512_cmp_epi64_mask(r, p, _MM_CMPINT_NLT), r, p);
}
template <std::uint32_t mod, int rows = 8>
__attribute__((target("avx512f,avx512dq"))) void product_packed_avx512(const std::int32_t *a, const std::int32_t *b, std::uint32_t *c, int n, int inner, int m) {
constexpr std::int64_t radius = mod / 2;
constexpr std::int64_t residue = (std::uint64_t(1) << 32) % mod;
constexpr std::int64_t folded_bound = (std::int64_t(1) << 31) * residue + 0xffffffffu;
constexpr int step = int(std::min<std::int64_t>(32, (std::numeric_limits<std::int64_t>::max() - folded_bound) / (radius * radius)));
int i = 0;
for (; i + rows <= n; i += rows) {
for (int j = 0; j < m; j += 16) {
const int width = std::min(16, m - j);
const __mmask16 active = (1u << width) - 1;
__m512i sums[rows][2];
for (int r = 0; r < rows; ++r) {
auto previous = _mm512_maskz_loadu_epi32(active, c + std::size_t(i + r) * m + j);
sums[r][0] = _mm512_and_si512(previous, _mm512_set1_epi64(0xffffffffu));
sums[r][1] = _mm512_srli_epi64(previous, 32);
}
for (int k = 0; k < inner; k += step) {
for (int t = k; t < std::min(inner, k + step); ++t) {
auto x = _mm512_maskz_loadu_epi32(active, b + std::size_t(j) * inner + std::size_t(t) * width);
auto y = _mm512_srli_epi64(x, 32);
for (int r = 0; r < rows; ++r) {
auto z = _mm512_set1_epi32(a[std::size_t(i + r) * inner + t]);
sums[r][0] = _mm512_add_epi64(sums[r][0], _mm512_mul_epi32(x, z));
sums[r][1] = _mm512_add_epi64(sums[r][1], _mm512_mul_epi32(y, z));
}
}
for (int r = 0; r < rows; ++r) for (int q = 0; q < 2; ++q) {
auto x = sums[r][q];
sums[r][q] = _mm512_add_epi64(_mm512_mul_epi32(_mm512_srli_epi64(x, 32), _mm512_set1_epi32(residue)), _mm512_and_si512(x, _mm512_set1_epi64(0xffffffffu)));
}
}
for (int r = 0; r < rows; ++r) {
auto even = reduce_product_avx512<mod>(sums[r][0]), odd = reduce_product_avx512<mod>(sums[r][1]);
_mm512_mask_storeu_epi32(c + std::size_t(i + r) * m + j, active, _mm512_or_si512(even, _mm512_slli_epi64(odd, 32)));
}
}
}
if constexpr (rows > 1) {
if (i < n) product_packed_avx512<mod, rows / 2>(a + std::size_t(i) * inner, b, c + std::size_t(i) * m, n - i, inner, m);
}
}
template <std::uint32_t mod, int rows = 4>
__attribute__((target("avx2"))) void product_packed_avx2(const std::int32_t *a, const std::int32_t *b, std::uint32_t *c, int n, int inner, int m) {
constexpr std::int64_t radius = mod / 2;
constexpr std::int64_t residue = (std::uint64_t(1) << 32) % mod;
constexpr std::int64_t folded_bound = (std::int64_t(1) << 31) * residue + 0xffffffffu;
constexpr int step = int(std::min<std::int64_t>(32, (std::numeric_limits<std::int64_t>::max() - folded_bound) / (radius * radius)));
auto reduce = [](std::int64_t sum) {
std::int64_t r = sum % std::int64_t(mod);
return std::uint32_t(r < 0 ? r + mod : r);
};
int i = 0;
for (; i + rows <= n; i += rows) {
for (int j = 0; j < m; j += 8) {
int width = std::min(8, m - j);
auto active = _mm256_cmpgt_epi32(_mm256_set1_epi32(width), _mm256_setr_epi32(0, 1, 2, 3, 4, 5, 6, 7));
__m256i sums[rows][2];
for (int r = 0; r < rows; ++r) {
auto previous = _mm256_maskload_epi32(reinterpret_cast<const int *>(c + std::size_t(i + r) * m + j), active);
sums[r][0] = _mm256_and_si256(previous, _mm256_set1_epi64x(0xffffffffu));
sums[r][1] = _mm256_srli_epi64(previous, 32);
}
for (int k = 0; k < inner; k += step) {
for (int t = k; t < std::min(inner, k + step); ++t) {
auto x = _mm256_maskload_epi32(b + std::size_t(j) * inner + std::size_t(t) * width, active);
auto y = _mm256_srli_epi64(x, 32);
for (int r = 0; r < rows; ++r) {
auto z = _mm256_set1_epi32(a[std::size_t(i + r) * inner + t]);
sums[r][0] = _mm256_add_epi64(sums[r][0], _mm256_mul_epi32(x, z));
sums[r][1] = _mm256_add_epi64(sums[r][1], _mm256_mul_epi32(y, z));
}
}
for (int r = 0; r < rows; ++r) for (int q = 0; q < 2; ++q) {
auto x = sums[r][q];
sums[r][q] = _mm256_add_epi64(_mm256_mul_epi32(_mm256_srli_epi64(x, 32), _mm256_set1_epi32(residue)), _mm256_and_si256(x, _mm256_set1_epi64x(0xffffffffu)));
}
}
for (int r = 0; r < rows; ++r) {
std::int64_t even[4], odd[4];
_mm256_storeu_si256(reinterpret_cast<__m256i *>(even), sums[r][0]);
_mm256_storeu_si256(reinterpret_cast<__m256i *>(odd), sums[r][1]);
std::uint32_t result[8];
for (int q = 0; q < 4; ++q) result[q * 2] = reduce(even[q]), result[q * 2 + 1] = reduce(odd[q]);
_mm256_maskstore_epi32(reinterpret_cast<int *>(c + std::size_t(i + r) * m + j), active, _mm256_loadu_si256(reinterpret_cast<const __m256i *>(result)));
}
}
}
if constexpr (rows == 4) {
if (i < n) product_packed_avx2<mod, 1>(a + std::size_t(i) * inner, b, c + std::size_t(i) * m, n - i, inner, m);
}
}
#endif
template <class T>
std::vector<T> multiply(const std::vector<T> &a, const std::vector<T> &b, int n, int inner, int m) {
std::vector<T> c(std::size_t(n) * m, T(0));
if (!n || !inner || !m) return c;
auto basic = [&] {
for (int i = 0; i < n; ++i) for (int k = 0; k < inner; ++k) {
const T &x = a[std::size_t(i) * inner + k];
for (int j = 0; j < m; ++j) c[std::size_t(i) * m + j] += x * b[std::size_t(k) * m + j];
}
};
if constexpr (small_modint<T>) {
if (std::uint64_t(n) * m <= 128u / unsigned(inner)) { basic(); return c; }
#if (defined(__x86_64__) || defined(__i386__)) && (defined(__GNUC__) || defined(__clang__))
if (inner >= 16 && m >= 8 && avx2()) {
const int block = avx512_product() ? 16 : 8;
std::vector<std::int32_t> x(a.size()), y(b.size());
std::vector<std::uint32_t> z(c.size());
auto center = [](std::uint32_t value) {
std::int32_t v = value;
return v <= std::int32_t((T::mod() - 1) / 2) ? v : v - std::int32_t(T::mod());
};
for (std::size_t i = 0; i < a.size(); ++i) x[i] = center(a[i].val());
for (int j = 0; j < m; j += block) {
int width = std::min(block, m - j);
for (int k = 0; k < inner; ++k) for (int s = 0; s < width; ++s)
y[std::size_t(j) * inner + std::size_t(k) * width + s] = center(b[std::size_t(k) * m + j + s].val());
}
if (block == 16) product_packed_avx512<T::mod()>(x.data(), y.data(), z.data(), n, inner, m);
else product_packed_avx2<T::mod()>(x.data(), y.data(), z.data(), n, inner, m);
for (std::size_t i = 0; i < c.size(); ++i) c[i] = T::raw(z[i]);
return c;
}
#endif
std::vector<std::uint32_t> x(a.size()), y(b.size()), z(c.size());
for (std::size_t i = 0; i < a.size(); ++i) x[i] = a[i].val();
for (std::size_t i = 0; i < b.size(); ++i) y[i] = b[i].val();
product_scalar<T::mod()>(x.data(), y.data(), z.data(), n, inner, m);
for (std::size_t i = 0; i < c.size(); ++i) c[i] = T::raw(z[i]);
} else basic();
return c;
}
#if defined(__GNUC__) && !defined(__clang__) && (defined(__x86_64__) || defined(__i386__))
#pragma GCC pop_options
#endif
}