https://blog.csdn.net/justidle/article/details/108794887 老师说的好文
老师的ppt:https://wwasf.lanzn.com/iMTkh4b19uof
密码:fnps
矩阵快速幂:
#include <iostream>
#include <cstring>
using namespace std;
typedef long long ll;
const int MOD = 1e9 + 7;
const int MAXN = 105;
struct Matrix {
ll mat[MAXN][MAXN];
Matrix() { memset(mat, 0, sizeof(mat)); }
};
int n;
Matrix mul(const Matrix &a, const Matrix &b) {
Matrix res;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
for (int k = 1; k <= n; k++) {
res.mat[i][j] = (res.mat[i][j] + a.mat[i][k] * b.mat[k][j]) % MOD;
}
}
}
return res;
}
// 矩阵快速幂:a^p
Matrix matrix_pow(Matrix a, ll p) {
Matrix res;
// 初始化为单位矩阵
for (int i = 1; i <= n; i++) res.mat[i][i] = 1;
while (p > 0) {
if (p & 1) {
res = mul(res, a);
}
a = mul(a, a);
p >>= 1;
}
return res;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
ll k;
cin >> n >> k;
Matrix A;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
cin >> A.mat[i][j];
A.mat[i][j] %= MOD;
if (A.mat[i][j] < 0) A.mat[i][j] += MOD; // 负数处理
}
}
Matrix ans = matrix_pow(A, k);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
cout << ans.mat[i][j] << " ";
}
cout << "\n";
}
return 0;
}线性方程:
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
const int MAXN = 55;
const double eps = 1e-8;
double mat[MAXN][MAXN];
int n;
int gauss() {
int rank = 0;
for (int col = 0; col < n; col++) { // 枚举每一列(变量)
// 1. 找主元:当前列,rank行往下,绝对值最大的一行
int main_row = rank;
for (int i = rank; i < n; i++) {
if (fabs(mat[i][col]) > fabs(mat[main_row][col])) {
main_row = i;
}
}
// 这一列全部是0,跳过,处理下一列
if (fabs(mat[main_row][col]) < eps) continue;
// 2. 交换当前rank行 和主元行
for (int j = col; j <= n; j++) {
swap(mat[rank][j], mat[main_row][j]);
}
// 3. 把主元行的主元位置归一化,主元变成1
double div = mat[rank][col];
for (int j = col; j <= n; j++) {
mat[rank][j] /= div;
}
// 4. 消去其他所有行的这一列
for (int i = 0; i < n; i++) {
if (i != rank && fabs(mat[i][col]) > eps) {
double factor = mat[i][col];
for (int j = col; j <= n; j++) {
mat[i][j] -= factor * mat[rank][j];
}
}
}
rank++;
}
// 判断无解 / 无穷多解
for (int i = rank; i < n; i++) {
if (fabs(mat[i][n]) > eps) {
// 0x1+0x2+... = 非0 → 矛盾,无解
return -1;
}
}
if (rank < n) {
// 秩小于未知数个数,无穷多解
return 0;
}
// 唯一解
return 1;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cin >> n;
for (int i = 0; i < n; i++) {
for (int j = 0; j <= n; j++) {
cin >> mat[i][j];
}
}
int res = gauss();
if (res == -1) {
cout << -1 << endl;
} else if (res == 0) {
cout << 0 << endl;
} else {
cout << fixed << setprecision(2);
for (int i = 0; i < n; i++) {
cout << "x" << i+1 << "=" << mat[i][n] << endl;
}
}
return 0;
}