蓝桥杯(矩阵幂运算)

幂运算

Posted by Zexin Zhang on December 10, 2017

注意单位矩阵

int main() {
	int n, m;
	int a[31][31];
	int ans[31][31];
	int b[31][31] = {0};
	memset(a, 0, sizeof(a));
	memset(ans, 0, sizeof(ans));
	scanf("%d%d", &n, &m);
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= n; j++) {
			scanf("%d", &a[i][j]);
			ans[i][j] = a[i][j];
		}
	}


	if (m == 0)
		for (int i = 1; i <= n; i++) {
			for (int j = 1; j <= n; j++) {
				if (i == j)
					printf("1 ");
				else
					printf("0 ");
			}
			printf("\n");
		}
	else if (m != 0) {

		for (int u = 1; u <= m - 1; u++) {
			for (int i = 1; i <= n; i++) {
				for (int j = 1; j <= n; j++) {
					for (int k = 1; k <= n; k++) {
						b[i][j] += ans[i][k] * a[k][j];
					}
				}
			}
			for (int i = 1; i <= n; i++) {
				for (int j = 1; j <= n; j++) {
					ans[i][j] = b[i][j];
					b[i][j] = 0;
				}
			}
		}
		for (int i = 1; i <= n; i++) {
			for (int j = 1; j <= n; j++) {
				printf("%d ", ans[i][j]);
			}
			printf("\n");
		}
	}
}