题目描述
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).
输入
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 a single integer representing fn modulo 1000000007 (109 + 7).
样例输入
2 3
3
样例输出
1
样例输入
0 -1
2
样例输出
1000000006
提示
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).
题意
题目给出递推关系。
类似于求斐波那契数列。
思路
用矩阵快速幂优化递推时间。
注意mod
关系。负数要%mod 再+mod 再%mod。
代码
#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <math.h>
#include <cstring>
#include <queue>
#include <map>
#include <vector>
#include <string>
#define mem(a) memset(a,0,sizeof(a))
#define mem2(a) memset(a,-1,sizeof(a))
#define mod 1000000007
#define mx 100005
using namespace std;
struct matrix
{
long long a[2][2];
};
matrix multiply (matrix x,matrix y)
{
matrix t;
for(int i=0; i<2; ++i)
for(int j=0; j<2; ++j)
{
t.a[i][j]=0;
for(int k=0; k<2; ++k)
t.a[i][j]=(t.a[i][j]+x.a[i][k]*y.a[k][j]%mod+mod)%mod;
}
return t;
}
matrix powmatrix (matrix x,long long y)
{
matrix t,temp;
for(int i=0; i<2; ++i)
for(int j=0; j<2; ++j)
{
if(i==j)
t.a[i][j]=1;
else
t.a[i][j]=0;
}
temp=x;
while(y)
{
if(y&1)
t=multiply(t,temp);
y>>=1;
temp=multiply(temp,temp);
}
return t;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("1.txt","r",stdin);
#endif // ONLINE_JUDGE
ios_base::sync_with_stdio(false);
cin.tie(0);
long long x,y;
long long n,ans;
matrix a,t;
while(cin>>x>>y)
{
cin>>n;
a.a[0][0]=1;
a.a[0][1]=-1;
a.a[1][0]=1;
a.a[1][1]=0;
if(n==1)
{
cout<<((x%mod)+mod)%mod<<endl;
continue;
}
if(n==2)
{
cout<<((y%mod)+mod)%mod<<endl;
continue;
}
t=powmatrix(a,n-2);
ans = t.a[0][0]*y%mod+t.a[0][1]*x%mod;
((ans%=mod)+=mod)%=mod;
cout<<ans<<endl;
}
return 0;
}