稀疏矩阵的乘法(数组)

Description

计算两个稀疏矩阵的乘法

Input

首先输入第一个矩阵的行数和列数,再输入该矩阵的三元组形式,以0 0 0结束
然后输入第二个矩阵的行数和列数,再输入该矩阵的三元组形式,以0 0 0结束

Output

输出相乘后的矩阵三元组。

  • Sample Input 
    3 3
    1 1 1
    2 2 2
    2 3 4
    3 1 -4
    0 0 0
    3 3
    1 3 -2
    2 3 -5
    3 1 8
    3 2 -6
    0 0 0
  • Sample Output
    1 3 -2
    2 1 32
    2 2 -24
    2 3 -10
    3 3 8

#include
#include 

int main()
{
	int *a[1000], *b[1000];
	
	int m1, n1, m2, n2;
	int x, y, z;
	int p, q;
	int i, j, sum = 0;

	for (i = 0; i< 1000; i++) {
		a[i] = (int*)malloc(1000 * sizeof(int));
		b[i] = (int*)malloc(1000 * sizeof(int));
		for (j = 0; j < 1000; j++){
			a[i][j] = 0;
			b[i][j] = 0;
		}
	}
	scanf("%d%d",&m1,&n1);
	while(1)
	{
		scanf("%d%d%d",&x,&y,&z);
		if(x == 0 && y == 0 && z == 0)
		{
			break;
		}
		a[x][y] = z;
	}
	scanf("%d%d",&m2,&n2);
	while(1)
	{
		scanf("%d%d%d",&x,&y,&z);
		if(x == 0 && y == 0 && z == 0)
		{
			break;
		}
		b[x][y] = z;
	}
	for(i = 1;i <= m1;i++)
	{
		for(j = 1;j <= n2;j++)
		{
			p = 1;
			q = 1;
			while(p <= n1)
			{
				sum += a[i][p]*b[q][j];
				p++;
				q++;
			}
			if(sum != 0)
			{
				printf("%d %d %d\n",i,j,sum);
			}
			sum = 0;
		}
	}
}



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