#include <stdio.h>
#include <stdlib.h>
#define MAX_ROW 4
#define MAX_COL 5
typedef struct element{
int row;
int col;
int value;
struct element *link;
}element;
typedef struct SparseType{
int num;
element *head;
element *rear;
}SparseType;
void sparse_matrix_cal(SparseType *s, int a[MAX_ROW][MAX_COL])
{
int i, j;
element *node;
for(i = 0; i < MAX_ROW; i++){
for(j = 0; j < MAX_COL; j++){
if(a[i][j] > 0){
node = (element *)malloc(sizeof(element));
if(node == NULL){
fprintf(stderr, "memory allocate error");
exit(1);
}
node->row = i;
node->col = j;
node->value = a[i][j];
s->num += 1;
if(s->head == NULL){
s->head = node;
s->rear = node;
node->link = NULL;
}
else
s->rear->link = node;{
s->rear = node;
node->link = NULL;
}
}
}
}
}
void sparse_matrix_add(SparseType *a, SparseType *b)
{
int i, j;
element *ax = a->head;
element *bx = b->head;
int cal[MAX_ROW][MAX_COL];
for(i = 0; i < MAX_ROW; i++){
for(j = 0; j < MAX_COL; j++){
cal[i][j] = 0;
}
}
while(ax != NULL){
if(ax->row == bx->row && ax->col == bx->col)
cal[ax->row][ax->col] = ax->value + bx->value;
else{
cal[ax->row][ax->col] = ax->value;
cal[bx->row][bx->col] = bx->value;
}
ax = ax->link;
bx = bx->link;
}
for(i = 0; i < MAX_ROW; i++){
for(j = 0; j < MAX_COL; j++)
printf("%d ",cal[i][j]);
printf("\n");
}
}
void init(SparseType *s)
{
s->num = 0;
s->head = NULL;
}
void sparse_matrix(int a[MAX_ROW][MAX_COL], int b[MAX_ROW][MAX_COL])
{
SparseType *s1;
SparseType *s2;
s1 = (SparseType *)malloc(sizeof(s1));
s2 = (SparseType *)malloc(sizeof(s2));
if(s1 == NULL || s2 == NULL){
fprintf(stderr, "memory allocate error");
exit(1);
}
init(s1);
init(s2);
sparse_matrix_cal(s1, a);
sparse_matrix_cal(s2, b);
sparse_matrix_add(s1,s2);
free(s1);
free(s2);
}
int main(void)
{
int a[MAX_ROW][MAX_COL] = {{1,0,0,0,0},
{0,2,0,0,0},
{0,0,3,0,0},
{0,0,0,4,0}};
int b[MAX_ROW][MAX_COL] = {{0,0,0,0,4},
{0,0,0,3,0},
{0,0,2,0,0},
{0,1,0,0,0}};
sparse_matrix(a,b);
}
만들어봤는데
이게 그냥 희소행렬 통짜로 계산하는거보다 퍼포먼스가 더좋음?
코드가 너무길어져서.. 내가 병신같이 만든건가?
댓글 0