洛谷P3390 矩陣快速冪模板

2020.6.16
最近要學數論和二分,數學工具必不可少。

矩陣快速冪昨天看到知乎有人講到,今天做到一道需要用矩陣才能做的題就回來打打基礎。矩陣快速冪就是矩陣鏈乘 + 快速冪運算。超級簡單。唯一不友好的一點是cpp的矩陣類真的魔鬼,md python程序員要是來用cpp處理數據估計能氣死了都。爲了能讓代碼正常地跑起來犧牲了好多封裝性了。氣死我了。行吧就這樣吧。

代碼:

#include <bits/stdc++.h>
using namespace std;
#define limit (100 + 5)//防止溢出
#define INF 0x3f3f3f3f
#define inf 0x3f3f3f3f3f
#define lowbit(i) i&(-i)//一步兩步
#define EPS 1e-6
#define FASTIO  ios::sync_with_stdio(false);cin.tie(0);
#define ff(a) printf("%d\n",a );
#define pi(a,b) pair<a,b>
#define rep(i, a, b) for(int i = a; i <= b ; ++i)
#define per(i, a, b) for(int i = b ; i >= a ; --i)
#define mint(a,b,c) min(min(a,b), c)
#define MOD 998244353
#define FOPEN freopen("C:\\Users\\tiany\\CLionProjects\\acm_01\\data.txt", "rt", stdin)
typedef long long ll;
typedef unsigned long long ull;
ll read(){
    ll sign = 1, x = 0;char s = getchar();
    while(s > '9' || s < '0' ){if(s == '-')sign = -1;s = getchar();}
    while(s >= '0' && s <= '9'){x = x * 10 + s - '0';s = getchar();}
    return x * sign;
}//快讀
void write(ll x){
    if(x < 0) putchar('-'),x = -x;
    if(x / 10) write(x / 10);
    putchar(x % 10 + '0');
}

int n ,m ;
ll k;
const ll mod = 1e9 + 7;
struct Matrix{
    ll mat[limit][limit];
    Matrix(){}
    ll mul(const Matrix &rhs, int x, int y){
        ll val = 0;
        rep(i ,1, n){
            (val += ((mat[x][i] * rhs.mat[i][y]) % mod)) %= mod;
        }
        return val % mod;
    }
    Matrix operator*(const Matrix & rhs){
        Matrix res;
        rep(i ,1, n){
            rep(j ,1, n){
                res.mat[i][j] = mul(rhs, i , j);
            }
        }
        return res;
    }
    void clear(){
        rep(i ,1, n)mat[i][i] = 1;
    }
    void print(){
        rep(i ,1, n){
            rep(j , 1, n){
                printf("%lld ",mat[i][j]);
            }
            puts("");
        }
    }
};
Matrix quickPow(Matrix base, ll expo){
    Matrix ans;
    ans.clear();//構造單位矩陣
    while (expo){
        if(expo & 1 )ans = ans * base;
        base = base * base;
        expo>>= 1;
    }
    return ans;
}
void operator<<(ostream &os, const Matrix &m){
    rep(i ,1 ,n){
        rep(j ,1, n){
            os<<m.mat[i][j]<<" ";
        }
        os<<endl;
    }
}
int main() {
#ifdef LOCAL
    FOPEN;
#endif
    n = read(), k = read();
    Matrix mat;
    rep(i ,1, n){
        rep(j ,1, n){
            mat.mat[i][j] = read();
        }
    }
    cout<<quickPow(mat, k);
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章