CodeForces - 450B Jzzhu and Sequences —— 斐波那契数、矩阵快速幂

本文提供了一种解决CodeForces-450B问题的有效方法,通过构造矩阵并使用快速幂运算来求解特定递推式的第n项。此递推式为斐波那契类型的序列,但采用减法而非加法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:https://vjudge.net/problem/CodeForces-450B

 

B. Jzzhu and Sequences
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

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).

Examples
input
2 3
3
output
1
input
0 -1
2
output
1000000006
Note

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).

 

 

题解:

斐波那契数,递推式为:f[n] = f[n-1] - f[n-2],构造矩阵如下:

 

 

代码如下:

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <algorithm>
 5 #include <vector>
 6 #include <cmath>
 7 #include <queue>
 8 #include <stack>
 9 #include <map>
10 #include <string>
11 #include <set>
12 using namespace std;
13 typedef long long LL;
14 const int INF = 2e9;
15 const LL LNF = 9e18;
16 const int MOD = 1e9+7;
17 const int MAXN = 1e6+100;
18 
19 const int Size = 2;
20 struct MA
21 {
22     LL mat[Size][Size];
23     void init()
24     {
25         for(int i = 0; i<Size; i++)
26         for(int j = 0; j<Size; j++)
27             mat[i][j] = (i==j);
28     }
29 };
30 
31 MA mul(MA x, MA y)
32 {
33     MA ret;
34     memset(ret.mat, 0, sizeof(ret.mat));
35     for(int i = 0; i<Size; i++)
36     for(int j = 0; j<Size; j++)
37     for(int k = 0; k<Size; k++)
38         ret.mat[i][j] += (1LL*x.mat[i][k]*y.mat[k][j])%MOD, ret.mat[i][j] %= MOD;
39     return ret;
40 }
41 
42 MA qpow(MA x, LL y)
43 {
44     MA s;
45     s.init();
46     while(y)
47     {
48         if(y&1) s = mul(s, x);
49         x = mul(x, x);
50         y >>= 1;
51     }
52     return s;
53 }
54 
55 MA tmp = {
56     1, -1,
57     1, 0
58 };
59 
60 int main()
61 {
62     LL f[3], n;
63     while(scanf("%lld%lld%lld",&f[1],&f[2],&n)!=EOF)
64     {
65         if(n<=2)
66         {
67             printf("%lld\n", (f[n]+MOD)%MOD);
68             continue;
69         }
70 
71         MA s = tmp;
72         s = qpow(s, n-2);
73         LL ans = (1LL*s.mat[0][0]*f[2]%MOD+1LL*s.mat[0][1]*f[1]%MOD+2*MOD)%MOD;
74         printf("%lld\n", ans);
75     }
76 }
View Code

 

转载于:https://www.cnblogs.com/DOLFAMINGO/p/8413061.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值