数据结构与算法-矩阵

稀疏矩阵的三元表存储运算问题

Posted by Zexin Zhang on October 22, 2017

副标题超唬人

/*
测试数据
3 3 3

1 1 1

1 2 7

2 2 4

3 3 3

1 2 9

2 3 4

3 3 5

*/
#include <bits/stdc++.h>

using namespace std;
#define maxx 1001;

typedef struct{
	int i,j;
	int v;
}node;
typedef struct{
	int m,n,t;                                
	node data[100];
}Spmatrix;
Spmatrix *scanSpmatrix(Spmatrix *A){
	printf("请输入矩阵的行数,列数及非0元素个数\n");
	scanf("%d%d%d",&(A->m),&(A->n),&(A->t));
	printf("建立三元组:\n");
	for(int i=0;i<A->t;i++){
		scanf("%d%d%d",&(A->data[i].i),&(A->data[i].j),&(A->data[i].v));
	}
	//printf("%d%d%d ",A->data[2].i,A->data[2].j,A->data[2].v);
	
	return A;
}
Spmatrix *cmpSpmatrix(Spmatrix *A,Spmatrix *B,Spmatrix *C){ 
	int ct=0;
	for(int i=0;i<A->t;i++){
		if( (A->data[i].i!=B->data[i].i) || (A->data[i].j!=B->data[i].j) ){    
			C->data[ct].i=A->data[i].i;
			C->data[ct].j=A->data[i].j;
			C->data[ct].v=A->data[i].v;
			ct++;
			C->data[ct].i=B->data[i].i;
			C->data[ct].j=B->data[i].j;
			C->data[ct].v=B->data[i].v;
			ct++;
		}
		if( (A->data[i].i==B->data[i].i) && (A->data[i].j==B->data[i].j) ){  
			C->data[ct].v=A->data[i].v+B->data[i].v;
			ct++;
		}

	}
	C->t=ct;
	return C;
}
Spmatrix *printSpmatrix(Spmatrix *A){
	for(int i=0;i<A->t;i++){
		if(A->data[i].v)
		printf("%d %d %d \n",A->data[i].i,A->data[i].j,A->data[i].v);
	}
}
Spmatrix *SelfprocessingSpmatrix(Spmatrix *C){
	int ct;
	for(int i=0;i<C->t;i++){
		for(int j=i+1;j<C->t;j++){
			if((C->data[i].i==C->data[j].i) && (C->data[i].j==C->data[j].j) ){
				C->data[i].v=(C->data[i].v) + (C->data[j].v);
				C->data[j].i=NULL;
				C->data[j].j=NULL;
				C->data[j].v=NULL;
				
			}
		}
	}
}
int main(){
	Spmatrix *A;
	A=(Spmatrix *)malloc(sizeof(Spmatrix));
	Spmatrix *B;
	B=(Spmatrix *)malloc(sizeof(Spmatrix));
	Spmatrix *C;
	C=(Spmatrix *)malloc(sizeof(Spmatrix));
	scanSpmatrix(A);
	scanSpmatrix(B);
	cmpSpmatrix(A,B,C);
	SelfprocessingSpmatrix(C);
	printf("\nA:\n");
	printSpmatrix(A);
	printf("\nB:\n");
	printSpmatrix(B);
	printf("\nC:\n");	
	printSpmatrix(C);

}