题目描述
给定三元组表示的稀疏矩阵,输出对应的矩阵
输入格式
输入包括一组测试数据,对应三元组表示的稀疏矩阵。
第一行为矩阵行数m,第二行为矩阵列数n,第三行为非零元个数t。 m,n都为小于100的正整数,t为小于10000的非负整数。
接下来t行为t个非零元的行、列、值,都是整数
输出格式
输出对应的稀疏矩阵
输入样例
m=3
n=2
t=1
1 1 5
输出样例
0 0
0 5
0 0
代码展示
把非零元存入链表再逐一进行判断比对,感觉有点麻烦了,但暂时没想到更简便的方法。
#include<bits/stdc++.h>
#include<iostream>
using namespace std;
struct Node{
int row;
int col;
int data;
Node *next;
};
int main(){
//freopen("/config/workspace/test/test","r",stdin);
int m,n,t;
scanf("m=%d\n",&m);
scanf("n=%d\n",&n);
scanf("t=%d\n",&t);
Node *head=new Node;
Node *tail=head;
head->next=NULL;
int r,c,d;
while(cin>>r>>c>>d){//将非零元数据存入链表
Node *p=new Node;
p->row=r;
p->col=c;
p->data=d;
if(head==NULL){
head->next=p;
tail=p;
}
else{
tail->next=p;
tail=p;
}
}
Node *q=head->next;//用来遍历
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(q!=NULL&&q->row==i&&q->col==j){
cout<<q->data<<' ';
q=q->next;
}
else cout<<0<<' ';
}
cout<<endl;
}
return 0;
}