#include<iostream>
#include<fstream>
using namespace std;
typedef pair<int,int> Point;
template<class T>
class Matrix{
private:
T* start;
int row;//行数
int col;//列数
public:
Matrix(){
start=NULL;row=0;col=0;
}
Matrix(Matrix<T>& m){//拷贝操作
row=m.getRow();col=m.getCol();
start=new T[row*col];
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
set(i,j,m.get(i,j));
}
}
}
Matrix(int i,int j){//构造i*j的matrix
start = new T[i*j];
row=i;col=j;
}
int getRow(){return row;}//获取行数
int getCol(){return col;}//获取列数
void init(T t){//用t初始化
T* p=start;
for(int i=0;i<row*col;i++){
*p++=t;
}
}
T get(int i,int j){return start[i*col+j];}//获取i行j列的数
void set(int i,int j,Matrix<T>& m){//设置 i行j列 处 的该块 矩阵为m
if(m.getCol()+j>this->col){
cout<<"size error\n";
return;
}
if(m.getRow()+i>this->row){
cout<<"size error\n";
return ;
}
for(int k=i;k<i+m.getRow();k++){
for(int l=j;l<j+m.getCol();l++){
set(k,l,m.get(k-i,l-j));
}
}
}
void set(T t){//设置4个顶角的值
set(0,0,t);set(0,col-1,t);set(row-1,0,t);set(row-1,col-1,t);
}
void set(int i,int j,T t){//设置i,j处为t
start[i*col+j]=t;
}
friend ostream& operator<<(ostream& o,Matrix<T>& m){//输出m
m.print(o);
return o;
}
void print(ostream& o){
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
o<<get(i,j)<<" ";
}
o<<endl;
}
}
~Matrix(){
delete []start;
}
Matrix<T> operator*(Matrix<T>& m){//矩阵乘法
if(col!=m.row){cout<<"error ! matrix's col isn't equal the second matrix's row\n";exit(0);}
Matrix<T> result(row,m.col);
for(int i=0;i<row;i++){
for(int j=0;j<m.col;j++){
T acc=T();
for(int k=0;k<col;k++){
acc+=get(i,k)*m.get(k,j);
}
result.set(i,j,acc);
}
}
return result;
}
Point find(T t){//查找t的位置
Point* p=new Point;
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
if(get(i,j)==t){
p->first=i;p->second=j;
}
}
}
return *p;
}
Matrix& operator=(Matrix<T>& m){//赋值操作
delete []start;
row=m.getRow();
col=m.getCol();
start=new T[row*col];
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
set(i,j,m.get(i,j));
}
}
return *this;
}
friend istream& operator>>(istream& i,Matrix<T>& m){
m.input(i);
return i;
}
void input(istream& i){
for(int j=0;j<row*col;j++){
i>>start[j];
}
}
};
template<typename T, int N>
Matrix<T> power(Matrix<T>& m,int n){//matrix m的n次方
ifstream f;f.open("E:\\matrix_identity.txt");//matrix_identity中存N*M的单位矩阵
Matrix<T> result(N,N);f>>result;
Matrix<T> tmp(N,N);tmp=m;
for(;n;n>>=1){
if(n&1){
result=result*tmp;
}
tmp=tmp*tmp;
}
return result;
}
int main(){
ifstream f2;f2.open("E:\\matrix_A.txt");
Matrix<int> a2(2,2);f2>>a2;
cout<<"fibonaci--a0=1;a1=1\ninput fibonaci's N\n";
int N;cin>>N;
Matrix<int> result=power<int,2>(a2,N-1);
cout<<"result is "<<result.get(0,0)+result.get(1,0)<<endl;// (A[n],A[n-1]) = (A[1],A[0]) * a2^(N-1)
f2.close();
system("pause");
}
E:\\matrix_A.txt中存放 1 1
1 0
E:\\matrix_identity中存放 1 0
0 1