标签:
1 //稀疏矩阵乘法 行逻辑链接的三元组顺序表 2 // 3 4 3 // 6 4 // 1 1 3 5 // 1 2 2 6 // 1 3 3 7 // 1 4 5 8 // 2 2 -1 9 // 3 1 2 10 // 4 2 11 // 5 12 // 1 2 2 13 // 2 1 1 14 // 3 1 -2 15 // 3 2 4 16 // 4 1 2 17 #include <iostream> 18 #include <cstring> 19 #define MAX_SIZE 2500+1 20 #define MAX_RC 2500+1 21 using namespace std; 22 typedef int elemType; 23 typedef struct { 24 int i,j; 25 elemType e; 26 }Triple; 27 typedef struct{ 28 Triple data[MAX_SIZE]; 29 int rowPos[MAX_RC];//各行第一个元素的秩表 30 int mu,nu,tu; 31 }TripleSpareMatrix; 32 void creatTripleSpareMatrix(TripleSpareMatrix &tSM) 33 { 34 scanf("%d%d%d",&tSM.mu,&tSM.nu,&tSM.tu); 35 int rowNum[tSM.mu+1]; 36 for (int i = 0; i < tSM.mu+1; ++i) rowNum[i]=0;//行元素数目累加器初始化 37 for(int k=1;k<=tSM.tu;k++) 38 { 39 scanf("%d%d%d",&tSM.data[k].i,&tSM.data[k].j,&tSM.data[k].e); 40 rowNum[tSM.data[k].i]++; 41 } 42 tSM.rowPos[1]=1; 43 for (int p = 2; p <=tSM.mu+1; ++p)//对不存在的第[tSm.mu+1]行统一处理 44 tSM.rowPos[p]=tSM.rowPos[p-1]+rowNum[p-1]; 45 } 46 void multMatrix(TripleSpareMatrix tSM1,TripleSpareMatrix tSM2,TripleSpareMatrix &tSM3) 47 { 48 tSM3.mu=tSM1.mu; tSM3.nu=tSM2.nu; tSM3.tu=0;//tSM3初始化 49 for (int row = 1; row <= tSM1.mu; ++row)//遍历tSM3(同tSM1)的每一行 50 { 51 int colNum[tSM2.nu+1]; 52 for (int i = 0; i < tSM2.nu+1; ++i) colNum[i]=0;//当前行个元素累加器初始化 53 tSM3.rowPos[row]=tSM3.tu+1;// 54 for (int p = tSM1.rowPos[row]; p <tSM1.rowPos[row+1]; ++p)//遍历当前的row行的每一个非零元 55 for (int q=tSM2.rowPos[tSM1.data[p].j]; q<tSM2.rowPos[tSM1.data[p].j+1]; ++q)//遍历与tSM1当前行的对应tSM2行(tSM1.data[p].j==tSM2.data[q].i) 56 colNum[tSM2.data[q].j]+=tSM1.data[p].e*tSM2.data[q].e;//累加 57 for (int col = 1; col <= tSM2.nu; ++col)//压缩存储非零元 58 if(colNum[col]) 59 { 60 tSM3.tu++; 61 tSM3.data[tSM3.tu].i=row; tSM3.data[tSM3.tu].j=col; tSM3.data[tSM3.tu].e=colNum[col]; 62 } 63 } 64 } 65 void printMatrix(TripleSpareMatrix tSM) 66 { 67 for (int i = 1; i <=tSM.tu; ++i) 68 printf("%d %d %d\n",tSM.data[i].i,tSM.data[i].j,tSM.data[i].e ); 69 } 70 int main(int argc, char const *argv[]) 71 { 72 #ifndef _OJ_ //ONLINE_JUDGE 73 freopen("input.txt", "r", stdin); 74 #endif 75 TripleSpareMatrix tSM1,tSM2,tSM3; 76 creatTripleSpareMatrix(tSM1); 77 creatTripleSpareMatrix(tSM2); 78 multMatrix(tSM1,tSM2,tSM3); 79 printMatrix(tSM3); 80 return 0; 81 }
标签:
原文地址:http://www.cnblogs.com/Code--Monkey/p/4290037.html