稀疏矩阵的乘法

博主备战2020考研,主要实现一些基础数据结构的代码,在此不会做过于详细讲解,仅仅放上代码。

#include 
#define MAX 55
using namespace std;
int A[MAX][3], B[MAX][3], C[MAX][3];
int numa, numb, numc, m, n, k;
pair findmuiltval(int I, int Z, int J)
{
	pair ans(0, 0);
	for (int i = 0; i < numa; i++) {
		if (A[i][1] == I && A[i][2] == Z) {
			ans.first = A[i][0];
			break;
		}
	}
	for (int i = 0; i < numb; i++) {
		if (B[i][1] == Z && B[i][2] == J) {
			ans.second = B[i][0];
			break;
		}
	}
	return ans;
}
void muilt()
{
	for (int i = 0; i < m; i++) {
		for (int j = 0; j < k; j++) {
			int sum = 0;
			for (int z = 0; z < n; z++) {
				pair val = findmuiltval(i, z, j);
				sum += (val.first * val.second);
			}
			if (sum != 0) {
				C[numc][0] = sum;
				C[numc][1] = i;
				C[numc][2] = j;
				numc++;
			}
		}
	}
}
void print(int Arr[][3], int num)
{
	for (int i = 0; i < num; i++) {
		cout << Arr[i][0] << ", " << Arr[i][1] << ", " << Arr[i][2] << endl;
	}
}
int main()
{
	int val;
	cin >> m >> n >> k;
	numa = 0;
	for (int i = 0; i < m; i++)
		for (int j = 0; j < n; j++) {
			cin >> val;
			if (val != 0) {
				A[numa][0] = val;
				A[numa][1] = i;
				A[numa][2] = j;
				numa++;
			}
		}
	numb = 0;	
	for (int i = 0; i < n; i++)
		for (int j = 0; j < k; j++) {
			cin >> val;
			if (val != 0) {
				B[numb][0] = val;
				B[numb][1] = i;
				B[numb][2] = j;
				numb++;
			}
		}	
	muilt();
	print(C, numc);
	return 0;
} 


/*
4 4
0 0 0 1
0 0 3 2
1 0 0 0
0 2 0 0

2 1 2
1
2
2 1
*/

 

你可能感兴趣的:(数据结构)