#include<iostream>
using namespace std;
typedef int ElemType;
#define MAXSIZE 100
//三元组顺序表定义
typedef struct {
int r;
int c;
ElemType d;
}TupNode;//三元组定义
typedef struct {
int nums;
TupNode* data;
}TSLis, * TSqList;//三元组顺序表定义
void CreatTSList(TSqList& A, TSqList& B) {
cin >> A->nums >> B->nums;
int i;
A->data = (TupNode*)malloc(MAXSIZE * sizeof(TupNode));
B->data = (TupNode*)malloc(MAXSIZE * sizeof(TupNode));
for (i = 0; i < A->nums; i++) {
cin >> A->data[i].r >> A->data[i].c >> A->data[i].d;
}
for (i = 0; i < B->nums; i++) {
cin >> B->data[i].r >> B->data[i].c >> B->data[i].d;
}
}
void Add(TSqList A, TSqList B, TSqList& C) {
int i = 0, j = 0, k = 0;
while (i < A->nums && j < B->nums) {
if (A->data[i].r < B->data[j].r) {//行查找
while (i < A->nums && j < B->nums && (A->data[i].r < B->data[j].r)) {
C->data[k].r = A->data[i].r;
C->data[k].c = A->data[i].c;
C->data[k].d = A->data[i].d;
C->nums++;
i++;
k++;
}
}
if (A->data[i].r < B->data[j].r) {
while (A->data[i].r > B->data[j].r) {
C->data[k].r = B->data[j].r;
C->data[k].c = B->data[j].c;
C->data[k].d = B->data[j].d;
C->nums++;
j++;
k++;
}
}
else if (A->data[i].r == B->data[j].r) {//列查找
if (A->data[i].c < B->data[j].c) {
C->data[k].r = A->data[i].r;
C->data[k].c = A->data[i].c;
C->data[k].d = A->data[i].d;
C->nums++;
i++;
k++;
}
if (A->data[i].c > B->data[j].c) {
C->data[k].r = B->data[j].r;
C->data[k].c = B->data[j].c;
C->data[k].d = B->data[j].d;
C->nums++;
j++;
k++;
}
else if (A->data[i].c == B->data[j].c) {//行列都相等的话求和
if (A->data[i].d + B->data[j].d != 0) {
C->data[k].r = A->data[i].r;
C->data[k].c = A->data[i].c;
C->data[k].d = A->data[i].d + B->data[j].d;
C->nums++;
k++;
}
i++;
j++;
}
}
}
while (i < A->nums) {//继续查找还有剩余元素的顺序表
C->data[k].r = A->data[i].r;
C->data[k].c = A->data[i].c;
C->data[k].d = A->data[i].d;
i++;
k++;
}
while (j < B->nums) {
C->data[k].r = B->data[j].r;
C->data[k].c = B->data[j].c;
C->data[k].d = B->data[j].d;
j++;
k++;
}
}
void Show(TSqList C) {
for (int i = 0; i < C->nums; i++) {
cout << C->data[i].r << " " << C->data[i].c << " " << C->data[i].d << endl;
}
}
int main() {
TSqList A, B, C;
A = (TSqList)malloc(sizeof(TSqList));
B = (TSqList)malloc(sizeof(TSqList));
C = (TSqList)malloc(sizeof(TSqList));
CreatTSList(A, B);
C->data = (TupNode*)malloc(MAXSIZE * sizeof(TupNode));
C->nums = 0;
Add(A, B, C);
Show(C);
return 0;
}