Codeforces#257 (Div. 2) B. Jzzhu and Sequences (数学

B. Jzzhu and Sequences

Description

Jzzhu has invented a kind of sequences, they meet the following property:
这里写图片描述

You are given x and y, please calculate fn modulo 1000000007 (109 + 7).

Input

The first line contains two integers x and y (|x|, |y| ≤ 109). The second line contains a single integer n (1 ≤ n ≤ 2·109).

Output

Output a single integer representing fn modulo 1000000007 (109 + 7).

Sample Input

2 3
3
0 -1
2

Sample Output

1
1000000006

Hint

In the first sample, f2 = f1 + f3, 3 = 2 + f3, f3 = 1.

In the second sample, f2 =  - 1;  - 1 modulo (109 + 7) equals (109 + 6).

题意

很明显的FIB的变形

题解:

可以矩阵快速幂, 把FIB的快速幂 初始状态改为

1 -1
1, 0

或者数学找规律 和6有关的周期

AC代码

矩阵快速幂

#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int mod = 1e9+7;
const int N = 2;
struct node {
    LL arr[N][N];
}p;
node mul(node x,node y)
{
    node ans;;
    memset(ans.arr,0,sizeof(ans.arr));
    for(int i = 0;i < 2; i++) {
        for(int j = 0;j < 2; j++) {
            for(int k = 0;k < 2; k++) {
                ans.arr[i][j] = (ans.arr[i][j]+(x.arr[i][k]*y.arr[k][j])%mod + mod)%mod;
            }
        }
    }
    return ans;
}
node powMod(LL u, node x)
{
    node ans;
    for(int i = 0; i < 2; i++)
        for(int j = 0; j < 2; j++) {
        if(i == j) ans.arr[i][j] = 1;
        else ans.arr[i][j] = 0;
    }
    while(u) {
        if(u&1) ans = mul(ans,x);
        x = mul(x,x);
        u >>= 1;
    }
    return ans;
}
int main()
{
    int x, y, p;
    cin>>x>>y>>p;
    if(p == 1) cout<<(x%mod+mod)%mod<<endl;
    else {
        node res;
        res.arr[0][0] = 1; res.arr[0][1] = -1;
        res.arr[1][0] = 1; res.arr[1][1] = 0;
        res = powMod(p-2,res);
        cout<<((y*res.arr[0][0]%mod + x*res.arr[0][1]%mod)%mod+mod)%mod<<endl;
    }
return 0;
}

数学规律

#include <bits/stdc++.h>
using namespace std;

#define LL long long
const int mod = 1e9+7;
LL arr[20];

int main()
{
    LL x, y, n;
    cin>>x>>y>>n;
    arr[0] = (x+mod)%mod;
    arr[1] = (y+mod)%mod;
    for(int i = 2; i < 6; i++) {
        arr[i] = (arr[i-1]-arr[i-2]+mod)%mod;
    }
    cout<<(arr[(n-1)%6]+mod)%mod<<endl;
return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值