#include<bits/stdc++.h>
#define M 6 //稀疏矩阵的行数
#define N 7 //稀疏矩阵的列数
#define MaxSize 50//稀疏矩阵中非零元素的最多个数
typedef int ElemType;
typedef struct
{
int r;
int c;
ElemType d;
}TupNode;
typedef struct
{
int rows;
int cols;
int nums;
TupNode data[MaxSize];
}TSMatrix;
//创建三元组
void GreateMat(TSMatrix &t,ElemType A[M][N])
{
int i,j;
t.rows=M;
t.cols=N;
t.nums=0;
for(i=0;i<M;i++)
{
for(j=0;j<N;j++)
{
if(A[i][j]!=0)
{
t.data[t.nums].r=i;
t.data[t.nums].c=j;
t.data[t.nums].d=A[i][j];
t.nums++;
}
}
}
}
//三元组赋值
bool Value(TSMatrix &t,ElemType x,int i,int j)
{
int k=0,k1;
if(i>=t.rows || j>=t.cols)
{
return false;
}
while(k<t.nums && i>t.data[k].r )
{
k++;
}
while(k<t.nums && i==t.data[k].r && j>t.data[k].c)
{
k++;
}
if(t.data[k].r==i && t.data[k].c==j)
{
t.data[k].d=x;
}
else
{
for(k1=t.nums-1;k1>=k;k1--)
{
t.data[k1+1].r=t.data[k1].r;
t.data[k1+1].c=t.data[k1].c;
t.data[k1+1].d=t.data[k1].d;
}
t.data[k].r=i;
t.data[k].c=j;
t.data[k].d=x;
t.nums++;
}
return true;
}
//将指定的元素值赋给变量
bool Assign(TSMatrix t,ElemType &x,int i,int j)
{
int k=0;
if(i>=t.nums && i>t.data[k].r)
{
k++;
}
while(k<t.nums && i==t.data[k].r && j>t.data[k].c)
{
k++;
}
while(k<t.nums && t.data[k].r && j>t.data[k].c)
{
k++;
}
if(t.data[k].r==i && t.data[k].c==j)
{
x=t.data[k].d;
}
else
{
x=0;
}
return true;
}
//输出三元组
void DispMat(TSMatrix t)
{
int k;
if(t.nums<=0)
{
return;
}
printf("\t%d\t%d\t%d\n",t.rows,t.cols,t.nums);
printf("\t--------\n");
for(k=0;k<t.nums;k++)
{
printf("\t%d\t%d\t%d\n",t.data[k].r,t.data[k].c,t.data[k].d);
}
}
int main()
{
TSMatrix t;
int i=0,j=0;
ElemType x=8;
int k=0,y=0;
ElemType l;
ElemType A[M][N]={ {0,0,1,0,0,0,0},
{0,2,0,0,0,0,0},
{3,0,0,0,0,0,0},
{0,0,0,5,0,0,0},
{0,0,0,0,6,0,0},
{0,0,0,0,0,7,4}};
GreateMat(t,A);
DispMat(t);
printf("\n");
Value(t,x,i,j); //8赋值第一个元素
DispMat(t);
Assign(t,l,k,y);
printf("%d",l);
return 0;
}