我目前正在做稀疏矩阵相加的问题。我正在使用三元组形式制作稀疏矩阵。三联体形式是利用c中的结构构成的。
struct sparse
{
int row;
int col;
int val;
};
但是在解决这个稀疏矩阵问题时,我遇到了一个问题,即当我以递增顺序给出非零值的索引时,我的代码仅显示正确的稀疏矩阵(例如(0 1 3),(1 2 5), (2 2 7) 等)否则它会显示不正确的矩阵。例如,如果我给出像 (0 1 3)、(2 2 7)、(1 2 5) 等这样的输入,那么它会显示错误的矩阵。如何解决这个问题,以便在任何索引顺序下都能给出正确的输出?
我已经添加了我的输入和结果输出。我已经对两个稀疏矩阵执行了此操作。
#include<iostream>
#include<cstdio>
struct sparse
{
int row,col,val;
};
void readmat(sparse sp[])
{
printf("enter total number number of rows ,column of matrix and total
of nonzero values in this\n");
scanf("%d %d %d",&sp[0].row,&sp[0].col,&sp[0].val);
printf("now start entering the values by specifying index
position\n");
for(int i=1;i<=sp[0].val;i++)
scanf("%d %d %d",&sp[i].row,&sp[i].col,&sp[i].val);
}
void displaymat(sparse sp[])
{
int k=1;
for(int i=0;i<sp[0].row;i++)
{
for(int j=0;j<sp[0].col;j++)
{
if(k<=sp[0].val&&i==sp[k].row&&j==sp[k].col)
{
printf("%d\t",sp[k].val);
k++;
}
else
printf("0\t");
}
printf("\n");
}
}
int main()
{
struct sparse sp1[10],sp2[10],sp3[10];
printf("for first matrix\n");
readmat(sp1);
printf("for second matrix\n");
readmat(sp2);
displaymat(sp1);
printf("\n\n");
displaymat(sp2);
printf("\n\n");
displaymat(sp3);
return 0;
}`
最佳答案
更新原来的答案:
乱序值没有被打印的原因是,当三元组形式的值指向更下方的元素时,for 循环会越过所有可以打印的其他值。例如,在您的示例中,第三个元素位于 row=1,col=3,但是第二个元素位于 row=2,col=2。这将导致外部 for 循环向下前进到第二行。此时循环将不会返回并打印第一行。
一种方法是根据行和列进行排序,然后打印值。
关于c - 使用 c 中的结构(三元组形式)添加稀疏矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45964814/