矩陣乘法(矩陣)【hpu】

點擊打開鏈接

矩陣乘法
Time Limit:1000MS     Memory Limit:131072KB     64bit IO Format:%lld & %llu

Description

給定兩個矩陣$A$和$B$,你需要判斷它們是否可以相乘,若可以請輸出相乘後的矩陣。

Input

第一行輸入一個整數$T$,代表有$T$組測試數據。

每組數據第一行輸入兩個整數$N,M$,代表矩陣$A$的行、列。

接下來$N$行,每行輸入$M$個整數$a[][]$。

之後一行輸入兩個整數$n,m$,代表矩陣$B$的行、列。

接下來$n$行,每行輸入$m$個整數$b[][]$。

注:$1 <= T <= 500,1 <= N,m <= 100,1 <= M,n <= 10,1 <= $矩陣元素$<= 20$。

Output

若矩陣$A、B$可以相乘,先輸出$YES$,再輸出相乘得到的矩陣。

對每行的矩陣元素,每兩個元素之間有一個空格,最後一個沒有空格。

反之輸出$NO$。

Sample Input

2
2 2
1 1
1 1
2 3
1 1 1
1 1 1
2 3
1 1 1
1 1 1
2 2
1 1
1 1 

Sample Output

YES
2 2 2
2 2 2
NO 

代碼:

#include <cstdio>
#include <algorithm>
using namespace std;
int a[105][105],b[105][105],c[105][105];
int main()
{
	int t;
	int N,M;
	int n,m;
	scanf("%d",&t);
	while(t--)
	{	
		scanf("%d %d",&N,&M);
		for(int i=0;i<N;i++)
		   for(int j=0;j<M;j++)
		scanf("%d",&a[i][j]);
		
		scanf("%d %d",&n,&m);
		for(int i=0;i<n;i++)
		   for(int j=0;j<m;j++)
		scanf("%d",&b[i][j]);
		if( M!=n )
       	printf("NO\n");
       	else
		{
			printf("YES\n");
				for(int i=0;i<N;i++)
	               for(int k=0;k<m;k++)
	           {
	           	      c[i][k]=0;        //注意,wa了好幾次全因爲這,艹 
		               for(int j=0;j<M;j++)
		           {
		              	c[i][k] += a[i][j]*b[j][k];
	               }
	           }
	           for(int i=0;i<N;i++)
              {
              	for(int j=0;j<m;j++)
	           	printf("%d%c",c[i][j],j==m-1?'\n':' ');
			  }
       	}

	}
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章