本题实现稀疏矩阵的求和运算。
函数接口定义:
int add_mat(elem a[],int t1,elem b[],int t2, elem c[]);//求a+b
其中 t1
和 t2
表示稀疏矩阵a的长度和稀疏矩阵b的长度,函数返回a+b的长度。
裁判测试程序样例:
#include <stdio.h>
#define M 10 //行
#define N 10 //列
typedef struct
{ int row, col; //行号、列号
int val;
}elem;
void input(elem a[],int m);
void show_mat(elem a[],int n);
int add_mat(elem a[],int t1,elem b[],int t2, elem c[]);
void input(elem a[],int m)
{
int i;
for(i=0;i<m;i++)
scanf("%d%d%d",&a[i].row,&a[i].col,&a[i].val);
}
void show_mat(elem a[],int n)//输出
{
int i;
for(i=0;i<n;i++)
printf("%d %d %d\n",a[i].row,a[i].col,a[i].val);
}
int main()
{
int t,m,n;
elem a[M*N],b[N*M],c[N*M];
scanf("%d%d",&m,&n);
input(a,m);
input(b,n);
t=add_mat(a,m,b,n,c);//c=a+b
show_mat(c,t);
return 0;
}
/* 请在这里填写答案 */
输入样例:
第一行为矩阵行和列,接下来为两个矩阵
3 2
0 0 1
0 1 3
2 1 2
0 1 -3
1 1 2
输出样例:
0 0 1
1 1 2
2 1 2
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
答案区:
int add_mat(elem a[],int t1,elem b[],int t2,elem c[])
{
elem z;
int s=0; //c中元素个数
int flag=1;
for(int k=0;k<t1;k++) //a遍历 找出a中的所有元素
{
flag=1;
for(int p=0;p<t2;p++) //b遍历
{
if(a[k].row==b[p].row&&a[k].col==b[p].col)
{
flag=0;
if(a[k].val+b[p].val!=0)
{
c[s].row=a[k].row;
c[s].col=a[k].col;
c[s].val=a[k].val+b[p].val;
s++;
}
}
}
if(flag)
{
c[s].row=a[k].row;
c[s].col=a[k].col;
c[s].val=a[k].val;
s++;
}
}
for(int k=0;k<t2;k++) //遍历b,找到a中没有的元素
{
flag=1;
for(int y=0;y<t1;y++)
{
if(b[k].row==a[y].row&&b[k].col==a[y].col)
{
flag=0;
continue;
}
}
if(flag)
{
c[s].row=b[k].row;
c[s].col=b[k].col;
c[s].val=b[k].val;
s++;
}
}
for(int q=0;q<s;q++) //冒泡排序法
{
for(int w=1;w<s;w++)
{
if(c[w-1].row>c[w].row)
{
z=c[w-1];
c[w-1]=c[w];
c[w]=z;
}
}
}
return s;
}