题目
思路
简单的遍历和条件判断。一直出现tls的问题,在看了谢哥博客之后才理解提示中“注意输入输出上的优化”指的是用scanf
和printf
,这俩比cin
和cout
快,替换了之后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;
}