您的位置:首页 > 其它

矩阵的基本变换 | Matrix

2016-03-31 13:32 375 查看
#include<bits/stdc++.h>

using namespace std;

#define max(x,y) Max(x,y)
#define min(x,y) Min(x,y)
#define REP(i,j,k) for (int i=(j),_end_=(k);i<=_end_;++i)
#define debug(...) fprintf(stderr,__VA_ARGS__)
#define pb push_back
#define ALL(x) ((x).begin()+1),(x).end()
#define SZ(x) (int((x).size()-1))

template <typename T> inline T Max(T x,T y){ return x > y ? x : y; }
template <typename T> inline T Min(T x,T y){ return x < y ? x : y; }

typedef long long LL;

const int dmax=1010,INF=0x3f3f3f3f,MOD=1e6+7;

int n;

struct matrix{
int n,m;
int mat[dmax][dmax];
matrix(){ memset(mat,0,sizeof(mat)); }
void powset(int n){
REP(i,1,n)
REP(j,1,n)
mat[i][j]=i==j;
}
void fibset(){ n=m=2; mat[1][1]=mat[1][2]=mat[2][1]=1; }
int fib(){ return mat[2][1]; }
void sizeset(int x,int y){ n=x,m=y; }
void clear(){ n=m=0; memset(mat,0,sizeof(mat)); }
void inversion(){
matrix tmp;
REP(i,1,n)
REP(j,1,m)
tmp.mat[j][i]=mat[i][j];
REP(i,1,n)
REP(j,1,m)
tmp.mat[j][i]=mat[i][j];
REP(i,1,m)
REP(j,1,n)
mat[i][j]=tmp.mat[i][j];
swap(n,m);
}
};

inline bool cmp(const matrix &x,const matrix &y){ return x.n==y.n && x.m==y.m; }
inline matrix operator +(matrix x,matrix y){
matrix tmp;
if (!cmp(x,y)){
debug("Matrix calc failed ( error = + )\n");
return tmp;
}
int n=x.n,m=x.m;
tmp.sizeset(n,m);
REP(i,1,n)
REP(j,1,m)
tmp.mat[i][j]=x.mat[i][j]+y.mat[i][j];
return tmp;
}
inline void operator +=(matrix &x,matrix y){ x=x+y; }
inline matrix operator *(matrix x,matrix y){
matrix tmp;
if (x.m!=y.n){
debug("Matrix calc failed ( error = * )\n");
return tmp;
}
int n=x.n,p=x.m,m=y.m;
tmp.sizeset(n,m);
REP(i,1,n)
REP(j,1,m)
REP(k,1,p)
tmp.mat[i][j]+=x.mat[i][k]*y.mat[k][j];
return tmp;
}
inline void operator *=(matrix &x,matrix y){ x=x*y; }
inline matrix operator ^(matrix x,int y){
matrix tmp;
tmp.powset(n);
tmp.sizeset(2,2);
while (y>0){
if (y&1)
tmp*=x;
x*=x;
y>>=1;
}
return tmp;
}
inline void fib(matrix &x,int y){ x=x^y; }
void init(matrix &x){
int n,m;
scanf("%d%d",&n,&m);
x.sizeset(n,m);
REP(i,1,x.n)
REP(j,1,x.m)
scanf("%d",&x.mat[i][j]);
}
void outit(matrix x){
REP(i,1,x.n)
REP(j,1,x.m)
printf("%d%c",x.mat[i][j],j==x.m?'\n':' ');
}
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
matrix x,y;
init(x);
init(y);
x+=y;
outit(x);
x.clear();
y.clear();
init(x);
init(y);
x*=y;
outit(x);
x.clear();
init(x);
x.inversion();
outit(x);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: