P1349 广义斐波那契数列

思路:简单矩阵快速幂,不过我x,y写反了,debug一小时。。。

#include<bits/stdc++.h>
#define INF 0x3f3f3f3f
#define ll long long
#define mem(ar,num) memset(ar,num,sizeof(ar))
#define me(ar) memset(ar,0,sizeof(ar))
#define lowbit(x) (x&(-x))
#define IOS ios::sync_with_stdio(false)
#define DEBUG cout<<endl<<"DEBUG"<<endl;
using namespace std;
//const ll mod = 1e9 + 7;
ll siz, p, q, n, m, x, y, mod;
struct mtx {
    ll x[2 + 1][2 + 1];
    mtx() {
        memset(x, 0, sizeof x);
    }
};
mtx operator *(const mtx &a, const mtx &b) {
    mtx c;
    for(int i = 0; i < siz; i++)
        for(int j = 0; j < siz; j++)
            for(int k = 0; k < siz; k++)
                c.x[i][j] = (c.x[i][j] + a.x[i][k] * b.x[k][j] % mod) % mod;
    return c;
}
mtx operator ^(mtx a, ll k) {
    mtx ret;
    for(int i = 0; i < siz; ++i)
        ret.x[i][i] = 1;
    while(k) {
        if(k & 1)
            ret = ret * a;
        a = a * a;
        k >>= 1;
    }
    return ret;
}
int main() {
    siz = 2;
    cin >> p >> q >> x >> y >> n >> mod;
    if(n == 1) {
        cout << x;
        return 0;
    }
    if(n == 2) {
        cout << y;
        return 0;
    }
    mtx ak;
    p %= mod, q %= mod;
    ak.x[0][0] = p;
    ak.x[0][1] = q;
    ak.x[1][0] = 1;
    mtx w;
    w = ak ^ (n - 2);
    ll ans = (y * w.x[0][0] % mod + x * w.x[0][1] % mod) % mod;
    cout << ans;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Endeavor_G/article/details/89062096