6-47 稀疏矩阵求和c

本题实现稀疏矩阵的求和运算。

函数接口定义:

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;
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值