三元组稀疏矩阵乘积高效c语言代码数据结构
时间: 2023-11-26 18:46:17 浏览: 144
三元组稀疏矩阵乘积是指两个稀疏矩阵相乘得到的结果仍为稀疏矩阵。下面是一个高效的C语言代码实现:
/* ---------------------------------------------------------------------------------------
功能:三元组稀疏矩阵乘积
参数:1、稀疏矩阵A 2、稀疏矩阵B 3、稀疏矩阵C指针
输出:OK、ERROR
*/
Status MultSMatrix(TSMatrix A, TSMatrix B, TSMatrix* C)
{
int i, j, k, p, q, tp, tq, ctemp;
int* ctempj = (int*)malloc((B.nu + 1) * sizeof(int));
if (!ctempj) exit(OVERFLOW);
for (j = 1; j <= B.nu; j++) ctempj[j] = 0;
C->mu = A.mu;
C->nu = B.nu;
C->tu = 0;
if (A.tu * B.tu != 0) {
for (i = 1; i <= A.mu; i++) {
C->rpos[i] = C->tu + 1;
if (i < A.mu) tp = A.rpos[i + 1];
else tp = A.tu + 1;
for (p = A.rpos[i]; p < tp; p++) {
j = A.data[p].j;
if (!ctempj[j]) {
for (q = 1; q <= B.nu; q++) ctempj[q] = 0;
for (q = B.rpos[j]; q < B.rpos[j + 1]; q++) {
k = B.data[q].j;
ctempj[k] = q;
}
}
if (ctempj[j]) {
tq = ctempj[j];
for (q = B.rpos[j]; q < B.rpos[j + 1]; q++) {
k = B.data[q].j;
if (ctempj[k] && ctempj[k] < tq) tq = ctempj[k];
if (ctempj[k] && ctempj[k] == tq) ctemp += B.data[q].e * A.data[p].e;
}
}
}
if (C->tu + B.nu > MAXSIZE) return ERROR;
if (ctemp) {
C->tu++;
C->data[C->tu].i = i;
C->data[C->tu].j = j;
C->data[C->tu].e = ctemp;
}
}
}
free(ctempj);
return OK;
}
阅读全文