【題目】Problem B.矩陣連乘

Problem B.矩陣連乘

題目描述
給你3個5*5的矩陣A、B、C,讓你求他們依次相乘的站果矩陣D,D=ABC

輸入描述
有多組數據,第一行是數據總數。
每組數據輸入三個5*5的矩陣,

輸出描述
輸出一個矩陣D即答案

樣例輸入

1
1 2 3 4 5
6 5 8 9 7
6 5 7 8 4
5 6 3 2 1
2 3 1 4 5

1 2 3 4 5
3 2 1 4 5
6 5 4 1 2
6 2 1 4 5
3 2 1 3 4

7 8 9 6 3
1 2 4 5 6
3 2 1 4 5
3 2 1 8 6
3 0 0 1 0

樣例輸出

886	  734   804   1112  832
2074  1700  1852  2634  2005
1791  1462  1589  2280  1740
942   722   770   134   954
848   662   710   1072  788

解答:

import java.util.Scanner;
/*
Problem B.矩陣連乘
題目描述
給你3個5*5的矩陣A、B、C,讓你求他們依次相乘的站果矩陣D,D=ABC,
輸入描述
有多組數據,第一行是數據總數。
每組數據輸入三個5*5的矩陣,
輸出描述
輸出一個矩陣D即答案
樣例輸入
1
1 2 3 4 5
6 5 8 9 7
6 5 7 8 4
5 6 3 2 1
2 3 1 4 5

1 2 3 4 5
3 2 1 4 5
6 5 4 1 2
6 2 1 4 5
3 2 1 3 4

7 8 9 6 3
1 2 4 5 6
3 2 1 4 5
3 2 1 8 6
3 0 0 1 0
樣例輸出
886 734 804 1112 832
2074 1700 1852 2634 2005
1791 1462 1589 2280 1740
942 722 770 134 954
848 662 710 1072 788
 */
public class Test{
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		while(scanner.hasNext()) {
			int n = scanner.nextInt();
			for(int t = 0; t < n; t++) {
				int[][] nums1 = new int[5][5];
				int[][] nums2 = new int[5][5];
				int[][] nums3 = new int[5][5];
				for(int i = 0; i < 5; i++) 
					for(int j = 0; j < 5; j++)
						nums1[i][j] = scanner.nextInt();
				for(int i = 0; i < 5; i++) 
					for(int j = 0; j < 5; j++)
						nums2[i][j] = scanner.nextInt();
				for(int i = 0; i < 5; i++) 
					for(int j = 0; j < 5; j++)
						nums3[i][j] = scanner.nextInt();
				nums1 = mSqual(nums1, nums2);
				nums1 = mSqual(nums1, nums3);
				for(int i = 0; i < 5; i++) {
					for(int j = 0; j < 5; j++)
						System.out.print(nums1[i][j] + " ");
					System.out.println();
				}
			}
		}
	}

	private static int[][] mSqual(int[][] nums1, int[][] nums2) {
		int[][] nums3 = new int[5][5];
		for(int i = 0; i < 5; i++) {
			for(int j = 0; j < 5; j++) {
				for(int k = 0; k < 5; k++) {
					nums3[i][j] += nums1[i][k] * nums2[k][j];
				}
			}
		}
		return nums3;
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章