-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSparseMatrixAdd.cpp
62 lines (56 loc) · 1.37 KB
/
SparseMatrixAdd.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include<bits/stdc++.h>
using namespace std;
class Element{
public:
int row,col,value;
};
vector<Element> SparseAddition(const vector<Element> &mat1,const vector<Element> &mat2){
vector<Element> result;
int i=0,j=0;
while (i<mat1.size() && j<mat2.size())
{
/* code */
if (mat1[i].row < mat2[j].row || (mat1[i].row == mat2[j].row && mat1[i].col < mat2[j].col)){
result.push_back(mat1[i]);
i++;
}
else if (mat1[i].row > mat2[j].row || (mat1[i].row == mat2[j].row && mat1[i].col > mat2[j].col)){
result.push_back(mat2[j]);
j++;
}
else {
result.push_back({mat1[i].row,mat1[i].col,mat1[i].value + mat2[j].value});
i++;
j++;
}
}
while (i < mat1.size())
{
/* code */
result.push_back(mat1[i]);
i++;
}
while (j < mat2.size())
{
/* code */
result.push_back(mat2[j]);
j++;
}
return result;
}
int main(){
vector<Element> mat1 = {
{0, 1, 3},
{1, 2, 4},
{2, 0, 1}
};
vector<Element> mat2 = {
{0, 1, 2},
{1, 2, 1},
{2, 0, 5}
};
vector<Element> result = SparseAddition(mat1,mat2);
for (const auto& element : result){
cout<<element.row<<" "<<element.col<<" "<<element.value<<endl;
}
}