数组与矩阵


10.13数组,矩阵(稀疏矩阵,特殊矩阵)

稀疏矩阵存储

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
63
64
65
66
67
typedef struct {
int i , j ;
int e;
} Triple;

typedef struct{
Triple data[MAXSIZE+1];
int mu , nu , tu ; //矩阵行数,列数,非零元个数
} TSMatrix;

void ReserveMatrix1(TSMatrix m,TSMatrix &n){ //一般转置,O(nu*tu)
int q;
n.tu = m.tu;
n.mu = m.nu;
n.nu = m.mu;
if (m.tu){
q = 1;
for (int col = 0; col < m.nu; ++col) { //列遍历
for (int j = 0; j < m.tu; ++j) {
if (m.data[j].j == col){
n.data[q].i = m.data[j].j;
n.data[q].j = m.data[j].i;
n.data[q].e = m.data[j].e;
q++;
}
}
}
}
}

void FastTransSMatrix(TSMatrix M , TSMatrix &T) //快速转置,O(nu+tu)
{
int col,t,p,q,cpot[100],num[100];
T.mu = M.nu; T.nu = M.mu ; T.tu = M.tu;
if(T.tu) {//num[col]表示矩阵M中第col列中非0元的个数
for(col=0 ; col<M.nu ; col++)
num[col]=0;
for(t=0 ; t<M.tu ; t++)
++num[ M.data[t].j ];
cpot[0]=0;
for(col=1 ; col<M.nu ; col++)
cpot[col] = cpot[col-1] + num[col-1];
for(p=0;p<M.tu;p++) {
col= M.data[p].j ; q=cpot[ col ] ;
T.data[q].i=M.data[p].j ;
T.data[q].j=M.data[p].i ;
T.data[q].e=M.data[p].e ;
++cpot[col] ; //cpot[col]表示M中col列下一个非0元在T.data中的位置
}//endfor
}//endif
}


void PrintMatrix(TSMatrix m){
int pp=0;
for (int i = 0; i < m.mu; ++i) {
for (int j = 0; j < m.nu; ++j) {
if ((m.data[pp].i == i)&&(m.data[pp].j == j)){
cout<<m.data[pp].e<<" ";
pp++;
} else{
cout<<0<<" ";
}
}
cout<<endl;
}
}
1
稀疏矩阵在转置时不能直接交换i,j的值,因为要考虑转置之后的顺序