矩陣快速冪 C++實現
阿新 • • 發佈:2018-12-24
花了兩天時間學習了矩陣快速冪和應用(基本就是拿來學應用上了,矩陣快速冪加外就學了五分鐘),基本故事就是發現演算法幾乎一點難度沒有(快速冪改變一下就完事了),難的是寫完…怎麼用啊,然後的故事就是惡補了幾個小時的線性代數的知識,從此矩陣快速冪的題目淪為數學題,咳咳,下面是程式碼
typedef long long LL;
const LL mod = 0;//該處初始化為0為了防止程式設計師沒初始化mod值。
inline LL modadd(LL a,LL b){ return ((a % mod) + (b % mod)) % mod; }
inline LL modsub(LL a,LL b){ return ((a % mod) - (b % mod) + mod) % mod; }
inline LL modmul(LL a,LL b){ return ((a % mod) * (b % mod)) % mod; }
const int MAXN = 4;
template<typename T>
struct matrix
{
T base[MAXN][MAXN];
size_t row,line;
matrix(size_t row,size_t line){
this -> row = row;
this -> line = line;
}
matrix(initializer_list<initializer_list<LL> > l){
row = l.size();
line = l.begin() -> size();
size_t j = 0 ;
auto iter1 = l.begin();
while(iter1 != l.end())
{
size_t k = 0;
auto iter2 = iter1 -> begin();
while(iter2 != iter1 -> end())
{
base[j][k] = *iter2;
iter2++,k++;
}
iter1++,j++;
}
}
matrix(const matrix & others){
row = others.row;
line = others.line;
for(size_t j = 0;j != row;j++)
for(size_t k = 0;k != line;k++)
base[j][k] = others[j][k];
}
friend matrix operator * (const matrix & lsh,const matrix & rsh){
matrix res(lsh.row,rsh.line);
memset(res.base , 0 ,sizeof(res.base));
for(size_t q = 0;q != lsh.line;q++)
for(size_t j = 0;j != lsh.row;j++)
if(lsh[j][q])
for(size_t k = 0;k != rsh.line;k++)
if(rsh[q][k])
res[j][k] = modadd(res[j][k] , modmul(lsh[j][q] , rsh[q][k]));
return res;
}
friend matrix pow(matrix a,LL n){
matrix res(a.row,a.line);
memset(res.base , 0 ,sizeof res.base);
for(size_t j = 0;j != a.row;j++)
res[j][j] = 1;
while(n) {
if(n & 1)
res = res * a;
a = a * a;
n >>= 1;
}
return res;
}
friend ostream & operator << (ostream & out,const matrix & rsh){
for(size_t j = 0;j != rsh.line * 2 + 1;j++)
out << "-";
out << endl;
for(size_t j = 0;j != rsh.row;j++)
{
for(size_t k = 0;k != rsh.line;k++)
out << "|" << rsh[j][k];
out << "|" << endl;
}
for(size_t j = 0;j != rsh.line * 2 + 1;j++)
out << "-";
out << endl;
return out;
}
T * operator[](size_t pos){
return base[pos];
}
const T * operator[](size_t pos)const{
return base[pos];
}
};