以三元组表存贮的稀疏矩阵A,B 非零元个数分别为m 和n。试完成程序,完成A+B。第一排为分别为A B元素的个数,以下各排分别输入对应的三元组,头m组为A中的元素,接下来为B的元素,同一个矩阵的元素按照先行后列排列,第一行规定为1,第一列规定为1
时间: 2024-05-08 07:15:21 浏览: 10
```python
class SparseMatrix:
def __init__(self, row, col, value):
self.row = row
self.col = col
self.value = value
@staticmethod
def create_from_triplet(m, n, triplet):
a_triplet = triplet[:m]
b_triplet = triplet[m:]
a = SparseMatrix(m, n, [])
b = SparseMatrix(m, n, [])
for i in range(m):
a.row.append(a_triplet[i][0])
a.col.append(a_triplet[i][1])
a.value.append(a_triplet[i][2])
for i in range(n):
b.row.append(b_triplet[i][0])
b.col.append(b_triplet[i][1])
b.value.append(b_triplet[i][2])
return a, b
def print(self):
for i in range(self.row[0]):
for j in range(self.col[0]):
if i + 1 == self.row[j+1] and j + 1 == self.col[j+1]:
print(self.value[j+1], end=' ')
else:
print(0, end=' ')
print()
# 测试
m, n = map(int, input().split())
triplet = []
for i in range(m+n):
triplet.append(tuple(map(int, input().split())))
a, b = SparseMatrix.create_from_triplet(m, n, triplet)
a.print()
b.print()
```