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;
}