以十字連結串列為儲存結構實現矩陣相加(嚴5.27)
阿新 • • 發佈:2019-01-10
Description
以十字連結串列為儲存結構,編寫程式,將稀疏矩陣B加到稀疏矩陣A上。
Input
第一行輸入四個正整數,分別為稀疏矩陣A和稀疏矩陣B的行數m、列數n、稀疏矩陣A的非零元素個數t1和稀疏矩陣B的非零元素個數t2。接下來的t1+t2行三元組表示,其中第一個元素表示非零元素所在的行值,第二個元素表示非零元素所在的列值,第三個元素表示非零元素的值。
Output
輸出相加後的矩陣三元組。
- Sample Input
3 4 3 2 1 1 1 1 3 1 2 2 2 1 2 1 2 2 3
- Sample Output
1 1 1 1 2 1 1 3 1 2 2 5
#include<stdio.h> #include<stdlib.h> #define MAXSIZE 100 typedef struct OLNode{ int i,j; int e; OLNode *right,*down; }OLNode,*OLink; typedef struct { OLink *rHead, *cHead; int mu,nu,tu;//行、列、非零元個數 }CrossList; void init(CrossList *M) { int m,n,t1; scanf("%d %d %d",&m,&n,&t1); M->mu=m; M->nu=n; M->tu=t1; M->rHead = (OLink *)malloc((m+1) * sizeof(OLink)); M->cHead = (OLink *)malloc((n+1) * sizeof(OLink)); int i; for(i=1;i<=m;i++) { M->rHead[i] = NULL; } for(i=1;i<=n;i++) { M->cHead[i] = NULL; } } void Create(CrossList *M) { int i,m,n,k,t2; scanf("%d",&t2); OLNode *q; for(i = 1;i <= M->tu;i++) { OLNode* p = (OLNode* )malloc(sizeof(OLNode)); scanf("%d %d %d",&m,&n,&k); p->i = m; p->j =n; p->e = k; if(M->rHead[m] == NULL||M->rHead[m]->j > n) { p->right = M->rHead[m]; M->rHead[m] = p; } else { for(q = M->rHead[m];(q->right)&&q->right->j < n;q = q->right); p->right = q->right; q->right = p; } if(M->cHead[n] == NULL || M->cHead[n]->i > m) { p->down = M->cHead[n]; M->cHead[n] = p; } else { for(q = M->cHead[n];(q->down)&&q->down->i < m;q = q->down); p->down = q->down; q->down = p; } } int flag = 0; for(i = 1;i <= t2;i++) { scanf("%d %d %d",&m,&n,&k); for(q = M->rHead[m];q;q = q->right) { if(q->j == n) { q->e += k; flag = 1; break; } } if(flag == 0) { OLNode* p = (OLNode* )malloc(sizeof(OLNode)); p->i = m;p->j = n;p->e = k; if(M->rHead[m] == NULL||M->rHead[m]->j > n) { p->right = M->rHead[m]; M->rHead[m] = p; } else { for(q = M->rHead[m];(q->right)&&q->right->j < n;q = q->right);//分號的作用是空迴圈,直接找到應該插入的位置 p->right = q->right; q->right = p; } if(M->cHead[n] == NULL || M->cHead[n]->i > m) { p->down = M->cHead[n]; M->cHead[n] = p; } else { for(q = M->cHead[n];(q->down)&&q->down->i < m;q = q->down); p->down = q->down; q->down = p; } } flag = 0; } } int main() { CrossList *A; A=(CrossList*)malloc(sizeof(CrossList)); init(A); Create(A); int i; OLink p; for(i=1;i<=A->mu;i++) { if(A->rHead[i] == NULL) { continue; } else { p = A->rHead[i]; while(p) { if(p->e == 0) { p = p->right; continue; } printf("%d %d %d\n",p->i,p->j,p->e); p = p->right; } } } return 0; }