2021秋季《数据结构》_EOJ 1049.三元组稀疏矩阵相加

题目

在这里插入图片描述

思路

简单的遍历和条件判断。一直出现tls的问题,在看了谢哥博客之后才理解提示中“注意输入输出上的优化”指的是用scanfprintf,这俩比cincout快,替换了之后1.2s不到过了。

代码

#include<bits/stdc++.h>
using namespace std;
#define MAX 2000000

typedef struct
{
	int rowIdx;
	int colIdx;
	int val;
}Tuple;

typedef struct
{
	int row;
	int col;
	int num;
	Tuple tupleList[MAX];
}Matrix;

Tuple* c = new Tuple[MAX];

int main()
{
	Matrix a, b;
	cin >> a.row >> a.col >> a.num;
	for (int i = 0; i < a.num; i++)
	{
	    scanf("%d %d %d",&a.tupleList[i].rowIdx,&a.tupleList[i].colIdx,&a.tupleList[i].val);
// 		cin >> a.tupleList[i].rowIdx >> a.tupleList[i].colIdx >> a.tupleList[i].val;
	}
	cin >> b.row >> b.col >> b.num;
	for (int i = 0; i < b.num; i++)
	{
	    scanf("%d %d %d",&b.tupleList[i].rowIdx,&b.tupleList[i].colIdx,&b.tupleList[i].val);
// 		cin >> b.tupleList[i].rowIdx >> b.tupleList[i].colIdx >> b.tupleList[i].val;
	}

	int i = 0, j = 0;
	int idx = 0;
	while (i < a.num && j < b.num)
	{
		if (a.tupleList[i].rowIdx == b.tupleList[j].rowIdx && a.tupleList[i].colIdx == b.tupleList[j].colIdx)
		{
			c[idx].rowIdx = a.tupleList[i].rowIdx;
			c[idx].colIdx = a.tupleList[i].colIdx;
			c[idx].val = a.tupleList[i].val + b.tupleList[j].val;
			idx++;
			i++;
			j++;
		}
		else if (a.tupleList[i].rowIdx < b.tupleList[j].rowIdx || (a.tupleList[i].rowIdx == b.tupleList[j].rowIdx && a.tupleList[i].colIdx < b.tupleList[j].colIdx))
		{
			c[idx].rowIdx = a.tupleList[i].rowIdx;
			c[idx].colIdx = a.tupleList[i].colIdx;
			c[idx].val = a.tupleList[i].val;
			idx++;
			i++;
		}
		else if (a.tupleList[i].rowIdx > b.tupleList[j].rowIdx || (a.tupleList[i].rowIdx == b.tupleList[j].rowIdx && a.tupleList[i].colIdx > b.tupleList[j].colIdx))
		{
			c[idx].rowIdx = b.tupleList[j].rowIdx;
			c[idx].colIdx = b.tupleList[j].colIdx;
			c[idx].val = b.tupleList[j].val;
			idx++;
			j++;
		}
	}
	while (i < a.num)
	{
		c[idx].rowIdx = a.tupleList[i].rowIdx;
		c[idx].colIdx = a.tupleList[i].colIdx;
		c[idx].val = a.tupleList[i].val;
		idx++;
		i++;
	}
	while (j < b.num)
	{
		c[idx].rowIdx = b.tupleList[j].rowIdx;
		c[idx].colIdx = b.tupleList[j].colIdx;
		c[idx].val = b.tupleList[j].val;
		idx++;
		j++;
	}
	for (int k = 0; k < idx; k++)
	{
	    printf("%d %d %d\n",c[k].rowIdx,c[k].colIdx,c[k].val);
		//cout << c[k].rowIdx << ' ' << c[k].colIdx << ' ' << c[k].val << endl;
	}

	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值