算法设计思路
本次实验主要采用三元表的方式来实现矩阵的建立,转置,相乘和相加,主要设计了一下函数
void init(Matrix &s)
- @description: 预处理函数
- @param {输入参数为 Matrix &s}
void cal(Matrix &s,int f)
- @description: 对三元表进行预处理函数
- @param {参数为 Matrix &s,int f}
- 若f为0则为对三元表s的列进行预处理,其中num存每列
- 的个数,copt则存每列的的第一个非零元元素的起始下标
- 若f为其他值则默认对三元表s的行进行预处理
void build(Matrix &s, int n, int m)
- @description: 建立三元表
本含函数采用输入n*m矩阵的方法进行输入
当输入值不为0时将其插入三元表中
void display(const Matrix &s)- @description: 展示函数
先按照输出三元表的方式输出三元表
再根据三元表输出相对应矩阵- @param: 输入参数为 const Matrix &s
void transpose(Matrix s, Matrix &t)
- @description: 转置矩阵函数
采用先对列进行预处理,其中num存储每行对应的非零元个数
copt则用来存储每行第一个非零元个数在三元表的存储下标- @param: 输入参数为 Matrix s, Matrix &t
在预处理完毕后对输入三元表S的元素顺序遍历,取出每一个
元素对应的列数,并开辟新变量存该元素对应在三元表中的
存储下标,根据存储下标来转置矩阵并存储在输出矩阵T中
同时将预处理的copt数组对应的下标位置进行自增,这样
反复做直至遍历完输入三元表S,该做法保证了输出的三元表
的顺序为顺序
void mult(Matrix s, Matrix t, Matrix &t2)
- @description: 矩阵相乘函数
- 值得注意的是矩阵相乘的前提条件 iff s.m == t.n 才有意义
- 且三元表若有一个为0个元素那结果肯定为空矩阵,以上两点并未
- 在代码中完整体现,请自行注意
- @param: 输入参数为 Matrix s, Matrix t, Matrix &t2
- 主要思路为先对s,t进行行元素个数,起始下标的预处理
- 在预处理完后,对s对应的矩阵按每行的顺序处理每一行的非零元
- 元素,对每个非零元元素记录其对应列数,并把其第列数作为行数下标
- 在t中找出对应行,然后相乘并将结果存在累加器cnt[]中,最后判断
- 累加器的每个元素是否为零,若不为零则存入输出三元表t2中
void add(Matrix s, Matrix t, Matrix &t3)
- @description: 矩阵相加函数
- @param {输入参数为 Matrix s, Matrix t, Matrix &t3}
- 采用map容器与pair容器相结合,pair用来存储每个非零元
- 元素对应的下标,pair的映射则为它的元素值,先顺序遍历
- s中的元素,将其存入map中,在顺序遍历t中元素,若其对应
- 的行列下标已存在,则进行元素值相加;若不存在,则建立
- 一个新的对象,将该元素存入map容器中;最后采用迭代器
- 顺序遍历map,若其映射元素不为零则将其存入结果三元表
- t3中,否则跳过。
代码如下
/*
* @Author: csc
* @Date: 2020-11-05 21:08:41
* @LastEditTime: 2020-11-13 14:33:23
* @Description: 矩阵的应用
*/
#include <iostream>
#include <algorithm>
#include <queue>
#include <string.h>
#include <map>
#include <cmath>
#include <cstdio>
#include <vector>
#define pr printf
#define sc scanf
#define sf(n) scanf("%d", &n)
#define sff(n1, n2) scanf("%d %d", &n1, &n2)
#define sfff(n1, n2, n3) scanf("%d %d %d", &n1, &n2, &n3)
#define sl(n) scanf("%lld", &n)
#define sll(n1, n2) scanf("%lld %lld", &n1, &n2)
#define slll(n1, n2, n3) scanf("%lld %lld %lld", &n1, &n2, &n3)
#define pb push_back
#define fi first
#define se second
const int N = 1e4 + 10;
typedef long long int ll;
using namespace std;
int a[100][100];
typedef struct
{
int row, col;
int value;
} triple;
typedef struct
/**
* @description: 三元表的定义
*/
{
int n, m, t;
triple data[N];
int num[110], copt[110];
} Matrix;
void init(Matrix &s)
/**
* @description: 预处理函数
* @param {输入参数为 Matrix &s}
*/
{
s.m = s.n = s.t = 0;
}
void cal(Matrix &s,int f)
/**
* @description: 对三元表进行预处理函数
* @param {参数为 Matrix &s,int f}
* 若f为0则为对三元表s的列进行预处理,其中num存每列
* 的个数,copt则存每列的的第一个非零元元素的起始下标
* 若f为其他值则默认对三元表s的行进行预处理
*/
{
int nm