萌心刚调矩阵114514秒,求大佬赐教
查看原帖
萌心刚调矩阵114514秒,求大佬赐教
490978
小超手123楼主2024/2/26 15:56

2只log的垃圾做法,样例过了,但第一个点就WA。

#include<bits/stdc++.h>
#define int long long
#define N 50
using namespace std;
struct node {
	int n, m;
	int a[N][N];
	friend node operator * (node x, node y) {
		node z;
		z.n = x.n, z.m = y.m;
		for(int i = 1; i <= z.n; i++)
		for(int j = 1; j <= z.m; j++)
			z.a[i][j] = 0;
		for(int i = 1; i <= z.n; i++)
		for(int j = 1; j <= z.m; j++)
		for(int k = 1; k <= x.m; k++)
			z.a[i][j] += x.a[i][k] * y.a[k][j];
		return z; 
	}
	friend node operator + (node x, node y) {
		node z;
		z.n = x.n, z.m = y.m;
		for(int i = 1; i <= z.n; i++)
		for(int j = 1; j <= z.m; j++)
			z.a[i][j] = x.a[i][j] + y.a[i][j];
		return z; 
	}
};
void init(node &x, int n, int m) {
	x.n = n, x.m = m;
	for(int i = 1; i <= n; i++)
	for(int j = 1; j <= m; j++) x.a[i][j] = 0;
}
node Pow(node A, int n) {
	node Ans;
	init(Ans, A.n, A.m);
	if(n == 0) {
		for(int i = 1; i <= Ans.n; i++)	Ans.a[i][i] = 1;
		return Ans;
	}
	if(n == 1) return A;
	node x = Pow(A, n / 2);
	if(n % 2 == 0) return x * x;
	else return x * x * A;
}
node Get(node A, int n) {
	if(n == 1) return A;
	node x = Pow(A, n / 2), mid = Get(A, n / 2);
	if(n % 2 == 0) return mid + (x * mid);
	else return mid + (x * mid) + Pow(A, n);
}
signed main() {
	int n, k;
	while(cin >> n >> k && n) {
		if(n == 0) break;
		node A;
		init(A, n, n);
		for(int i = 1; i <= n; i++)
		for(int j = 1; j <= n; j++) cin >> A.a[i][j];
		node Ans = Get(A, n);
		for(int i = 1; i <= n; i++) {
			for(int j = 1; j <= n; j++) 
				if(j != n) cout << Ans.a[i][j] << " ";
				else cout << Ans.a[i][j];
			cout << endl;
		}
		cout << endl;
	}
	return 0;
}
2024/2/26 15:56
加载中...