import java.util.*;
public class Triple {
public static void main(String args[]) {
Scanner in=new Scanner(System.in);
while(in.hasNext()) {
int n=in.nextInt();
Mat mat=new Mat(n,n+1);
int m=in.nextInt();
for(int i=0;i<m;i++) {
int row=in.nextInt();
int col=in.nextInt();
int value=in.nextInt();
mat.Insert(row, col+2, value);
}
Mat mat4=add(mat,mat);
mat4.Print();
Mat mat5=sub(mat4,mat);
mat.Print();
}
}
//矩阵加法
public static Mat add(Mat mat1,Mat mat2) {
Mat mat3=new Mat(mat1.rows,mat1.cols);
if(mat1.cols!=mat2.cols || mat1.rows!=mat2.rows) {
System.out.println("两个矩阵大小不一致,无法相加");
}else {
Map<String,Integer> map=new HashMap<String,Integer>();
for(int i=0;i<mat1.list.size();i++) {
Tri temp=mat1.list.get(i);
map.put(temp.row+" "+temp.col,temp.value);
}
for(int i=0;i<mat2.list.size();i++) {
Tri temp=mat2.list.get(i);
String str=temp.row+" "+temp.col;
int value=temp.value;
if(map.containsKey(str)) {
int tempvalue=map.get(str)+value;
map.remove(str);
map.put(str, tempvalue);
}else {
map.put(str,value);
}
}
System.out.println("map");
for(String key:map.keySet()) {
String str1=key;
String str2[]=str1.split(" ");
mat3.Insert(Integer.valueOf(str2[0]), Integer.valueOf(str2[1]), map.get(key));
}
}
return mat3;
}
//矩阵减法
public static Mat sub(Mat mat1,Mat mat2) {
Mat mat3=new Mat(mat1.rows,mat1.cols);
if(mat1.cols!=mat2.cols || mat1.rows!=mat2.rows) {
System.out.println("两个矩阵大小不一致,无法相减");
}else {
Map<String,Integer> map=new HashMap<String,Integer>();
for(int i=0;i<mat1.list.size();i++) {
Tri temp=mat1.list.get(i);
map.put(temp.row+" "+temp.col,temp.value);
}
for(int i=0;i<mat2.list.size();i++) {
Tri temp=mat2.list.get(i);
String str=temp.row+" "+temp.col;
int value=temp.value;
if(map.containsKey(str)) {
int tempvalue=map.get(str)-value;
map.put(str, tempvalue);
}else {
map.put(str,(-1)*value);
}
}
for(String key:map.keySet()) {
String str1=key;
String str2[]=str1.split(" ");
mat3.Insert(Integer.valueOf(str2[0]), Integer.valueOf(str2[1]), map.get(key));
}
}
return mat3;
}
}
//定义三元组
class Tri{
int row;
int col;
int value;
Tri(int row,int col,int value){
this.row=row;
this.col=col;
this.value=value;
}
}
//定义矩阵
class Mat{
int rows;
int cols;
public List<Tri> list=new ArrayList<Tri>();
Mat(int rows,int cols){
this.rows=rows;
this.cols=cols;
}
public void Insert(int row,int col,int value) {
list.add(new Tri(row,col,value));
}
//矩阵转置
public void Reverse() {
for(int i=0;i<list.size();i++) {
Tri temp=new Tri(list.get(i).row,list.get(i).col,list.get(i).value);
list.get(i).col=temp.row;
list.get(i).row=temp.col;
}
}
//打印
public void Print() {
for(int i=0;i<list.size();i++) {
Tri temp=list.get(i);
System.out.println("("+temp.row+","+temp.col+")="+temp.value);
}
}
}
三元组实现矩阵的加法和减法(未除去0)
最新推荐文章于 2023-08-01 14:35:18 发布