Skip to content

矩阵

矩阵乘法

cpp
template <class T>
vec2d<T> operator*(const vec2d<T> &lhs, const vec2d<T> &rhs) {
	assert(lhs.y == rhs.x);
	vec2d<T> u(lhs.x, rhs.y);
	for (int i = 0; i < lhs.x; i++) {
		for (int k = 0; k < rhs.x; k++) {
			T t = lhs[i][k];
			for (int j = 0; j < rhs.y; j++)
				u[i][j] += rhs[k][j] * t;
		}
	}
	return u;
}

template <class T>
std::istream &operator>>(std::istream &is, vec2d<T> &m) {
	for (int i = 0; i < m.x * m.y; i++)
		is >> m.m[i];
	return is;
}

template <class T>
std::ostream &operator<<(std::ostream &os, const vec2d<T> &m) {
	for (int i = 0; i < m.x * m.y; i++)
		os << m.m[i] << " \n"[(i + 1) % m.y == 0];
	return os;
}

矩阵快速幂

cpp
template <class T>
auto make_matrix_E(int n) {
	vec2d<T> ret(n, n);
	for (int i = 0; i < n; i++)
		ret[i][i] = 1;
	return ret;
}

template <class T>
auto matrix_pow(vec2d<T> a, i64 w) {
	auto ret = make_matrix_E<T>(a.x);
	for (; w > 0; w /= 2) {
		if (w & 1)
			ret = a * ret;
		a = a * a;
	}
	return ret;
}

矩阵 IO

cpp
template <class T>
std::istream &operator>>(std::istream &is, vec2d<T> &m) {
	for (int i = 0; i < m.x * m.y; i++)
		is >> m.m[i];
	return is;
}

template <class T>
std::ostream &operator<<(std::ostream &os, const vec2d<T> &m) {
	for (int i = 0; i < m.x * m.y; i++)
		os << m.m[i] << " \n"[(i + 1) % m.y == 0];
	return os;
}