稀疏矩阵加法(PTA)使用map为什么不对中间两个测试的怎么都过不了?

#include <iostream>
#include<map>
using namespace std;

int ansindex = 0;
pair<int, int>ans[1000];

int main()
{
	map<int, int>maps;
	int row, col;
	cin >> row >> col;
	int times = 0;
	cin >> times;
	for (int i = 0; i < times; i++) {
		int x, y, z;
		cin >> x >> y >> z;
		int index = x * col + y + 1;
		int value = z;
		if (maps.find(index) == maps.end()) {
			maps.insert(pair<int, int>(index, value));
		}
		else {
			maps[index] = maps[index] + value;
		}
	}
	cin >> times;
	for (int i = 0; i < times; i++) {
		int x, y, z;
		cin >> x >> y >> z;
		int index = x * col + y + 1;
		int value = z;
		if (maps.find(index) == maps.end()) {
			maps.insert(pair<int, int>(index, value));
		}
		else {
			maps[index] = maps[index] + value;
		}
	}


	std::map<int, int>::iterator it = maps.begin();
	for (; it != maps.end();)
	{
		if (it->second == 0)
		{
			maps.erase(it++);
		}
		else {
			it++;
		}
	}


	if (maps.size() == 0) {
		cout << maps.size();
	}
	else {
		cout << maps.size() << endl;
		it = maps.begin();
		if (!maps.empty()) {
			while (it != maps.end()) {
				ans[ansindex].first = it->first;
				ans[ansindex++].second = it->second;
				it++;
			}
		}

		for (int i = 0; i < ansindex - 1; i++) {
			int nowrow = 0;
			while (ans[i].first > col) {
				ans[i].first -= col;
				nowrow++;
			}
			int nowcol = ans[i].first-1;
			cout << nowrow << " " << nowcol << " " << ans[i].second << endl;
		}
		if (ansindex != 0) {
			int nowrow = 0;
			while (ans[ansindex - 1].first > col) {
				ans[ansindex-1].first -= col;
				nowrow++;
			}
			int nowcol = ans[ansindex - 1].first-1;
			cout << nowrow << " " << nowcol << " " << ans[ansindex - 1].second;
		}
	}
		system("pause");
		return 0;
	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值