1. 题目
示例输入
3 4 3 2
1 1 1
1 3 1
2 2 2
1 2 1
2 2 3
示例输出
1 1 1
1 2 1
1 3 1
2 2 5
2. 代码
虽然好像和理论课noj上差不多,但是为了交作业还是写成稍微好看一点的样子吧。
//3 4 3 2
//1 1 1
//1 3 1
//2 2 2
//1 2 1
//2 2 3
#include <iostream>
#define MAXSIZE 1000
#define ElemType int
using namespace std;
typedef struct{
int row, col;
ElemType e;
}Triple;
typedef struct{
Triple data[MAXSIZE];
int m, n, len;
}TSMatrix;
//要么传指针*, 要么传引用&(C++),否则改变不能传回main函数
//之前都直接用了结构体,改成指针有点麻烦,就传引用&了
void InputMatrix(TSMatrix &M, int t){
for(int i=0; i<t; i++){
cin >> M.data[i].row >> M.data[i].col >> M.data[i].e;
}
M.len = t;
}
// 每次将一个三元组移到C中时的操作相同,故提取出来作为一个函数便于复用
void add_to(TSMatrix &M, int &m, TSMatrix &N, int &n){
N.data[n].row = M.data[m].row;
N.data[n].col = M.data[m].col;
N.data[n].e = M.data[m].e;
n++;m++;
}
void Add(TSMatrix &A, TSMatrix &B, TSMatrix &C){
int a = 0, b = 0, c = 0;
while(a < A.len && b < B.len){
if(A.data[a].row == B.data[b].row){
int r = A.data[a].row;
// 注意每次使用循环都要判断是否越界,否则就会死循环了
while(A.data[a].row == r && B.data[b].row == r && a < A.len && b < B.len){
if(A.data[a].col == B.data[b].col){
int out = A.data[a].e + B.data[b].e;
if(out!=0){
C.data[c].row = r;
C.data[c].col = A.data[a].col;
C.data[c].e = out;
c++;
}
a++; b++;
}
else if(A.data[a].col < B.data[b].col) add_to(A, a, C, c);
else add_to(B, b, C, c);
}
}
else if(A.data[a].row < B.data[b].row) add_to(A, a, C, c);
else add_to(B, b, C, c);
}
while(a < A.len) add_to(A, a, C, c);
while(b < B.len) add_to(B, b, C, c);
C.len = c;
}
void OutputMatrix(TSMatrix &M){
for(int i=0; i<M.len; i++){
cout << M.data[i].row << " " << M.data[i].col << " " << M.data[i].e << endl;
}
}
int main(int argc, char** argv) {
TSMatrix A, B, C;
int m, n, t1, t2;
cin >> m >> n >> t1 >> t2;
A.m = B.m = C.m = m;
A.n = B.n = C.n = n;
InputMatrix(A, t1);
InputMatrix(B, t2);
Add(A, B, C);
OutputMatrix(C);
return 0;
}