Codeforces 450B Jzzhu and Sequences(矩阵快速幂)

248 篇文章 0 订阅

题目链接:Codeforces 450B Jzzhu and Sequences

题目大意:给定序列f1=x, f2=y,fi=fi+1fi1,求fn

解题思路:矩阵快速幂。

#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;
typedef long long ll;
const ll mod = 1e9+7;

ll s[2][2] = {1, 0, 0, 1};

void mat_mod (ll a[2][2], ll b[2][2]) {
    ll c[2][2];
    memset(c, 0, sizeof(c));
    for (int k = 0; k < 2; k++) {
        for (int i = 0; i < 2; i++)
            for (int j = 0; j < 2; j++)
                c[i][j] = ((c[i][j] + a[i][k] * b[k][j]) % mod + mod) % mod;
    }
    memcpy(a, c, sizeof(c));
}

void mat_pow(int n) {
    ll x[2][2] = {0, 1, -1, 1};
    while (n) {
        if (n&1)
            mat_mod(s, x);
        mat_mod(x, x);
        n >>= 1;
    }
}

int main () {
    int x, y, n;
    scanf("%d%d%d", &x, &y, &n);
    if (n == 1)
        printf("%lld\n", (x % mod + mod) % mod);
    else {
        mat_pow(n-2);
        printf("%lld\n", ((x * s[1][0] % mod + y * s[1][1] % mod) % mod + mod) % mod);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值