洛谷P1939 矩陣加速 (矩陣快速冪)

2020.6.17
等下一篇再來說,這個就是爲了做一道綠題練習地矩陣加速地方法。學過線性代數的應該都不會覺得很難。

代碼:

#include <bits/stdc++.h>
using namespace std;
#define limit (10 + 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 ,k;
const int mod = 1e9 + 7;
struct matrix {
    ll mat[limit][limit];

    matrix() {
        memset(mat, 0 , sizeof(mat));
    }
    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;
    }
    static matrix norm() {//單位向量
        matrix ans;
        rep(i ,1, n)ans.mat[i][i] = 1;
        return ans;
    }
    void set(int i, int j, ll val){
        mat[i][j] = val;
    }
};
void operator<<(ostream &os, const matrix &m){
    rep(i ,1 ,n){
        rep(j ,1, n){
            os<<m.mat[i][j]<<" ";
        }
        os<<endl;
    }
}
matrix quickPow(matrix base, ll expo){
    matrix ans = matrix::norm();//構造單位矩陣
    while (expo){
        if(expo & 1 )ans = ans * base;
        base = base * base;
        expo >>= 1;
    }
    return ans;
}
int t;
int main() {
#ifdef LOCAL
    FOPEN;
#endif
    matrix ans;
    ans.set(1,1,1);
    ans.set(1,3,1);
    ans.set(2,1,1);
    ans.set(3,2,1);//四個地方
    t = read();
    n = 3;
    rep(i ,1, t){
        k = read();
        if(k <= 3){
            write(1), putchar('\n');
            continue;
        }
        matrix res = quickPow(ans, k);
        ff(res.mat[2][1])
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章