资源限制
时间限制:1.0s 内存限制:512.0MB
问题描述
给定一个N阶矩阵A,输出A的M次幂(M是非负整数)
例如:
A =
1 2
3 4
A的2次幂
7 10
15 22
输入格式
第一行是一个正整数N、M(1<=N<=30, 0<=M<=5),表示矩阵A的阶数和要求的幂数
接下来N行,每行N个绝对值不超过10的非负整数,描述矩阵A的值
输出格式
输出共N行,每行N个整数,表示A的M次幂所对应的矩阵。相邻的数之间用一个空格隔开
样例输入
2 2
1 2
3 4
样例输出
7 10
15 22
这题用简单的矩阵相乘就可以做了,但要注意,m为0的时候是单位矩阵,我用快速幂矩阵做
代码一:
import java.util.Arrays;
import java.util.Scanner;
public class Demo04 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int [][]a = new int[n][n];
int [][]c = new int[n][n];
int [][]result = new int [n][n];
for (int i = 0; i < n; i++) {
result[i][i] = 1;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = sc.nextInt();
}
}
while(m-- > 0){
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
c[i][j] = 0;
for (int k = 0; k < n; k++) {
c[i][j] += a[i][k] * result[k][j];
}
}
}
for (int i = 0; i < n; i++) {
System.arraycopy(c[i], 0, result[i], 0, n);
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if(j != n-1){
System.out.print(result[i][j] + " ");
}else{
System.out.println(result[i][j]);
}
}
}
}
}
代码二:
import java.util.Arrays;
import java.util.Scanner;
public class Demo04 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int [][]a = new int[n][n];
int [][]c = new int[n][n];
int [][]result = new int [n][n];
for (int i = 0; i < n; i++) {
result[i][i] = 1;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = sc.nextInt();
}
}
while(m > 0){
if(m % 2 == 1){
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
c[i][j] = 0;
for (int k = 0; k < n; k++) {
c[i][j] += a[i][k] * result[k][j];
}
}
}
for (int i = 0; i < n; i++) {
System.arraycopy(c[i], 0, result[i], 0, n);//将c数组赋值给result数组
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
c[i][j] = 0;
for (int k = 0; k < n; k++) {
c[i][j] += a[i][k] * a[k][j];
}
}
}
for (int i = 0; i < n; i++) {
System.arraycopy(c[i], 0, a[i], 0, n);
}
m /= 2;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if(j != n-1){
System.out.print(result[i][j] + " ");
}else{
System.out.println(result[i][j]);
}
}
}
}
}