Jzzhu and Sequences
Jzzhu has invented a kind of sequences, they meet the following property:
You are given x and y, please calculate fn modulo 1000000007 (
1
0
9
+
7
10^9 + 7
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·
1
0
9
+
7
10^9 + 7
109 + 7).
Output
Output a single integer representing fn modulo 1000000007 (
1
0
9
+
7
10^9 + 7
109 + 7).
Examples
input
2 3
3
output
1
input
0 -1
2
output
1000000006
题意
求数列第n项
题解
矩阵快速幂,水题,懒得敲,直接把模板复制粘贴了
代码
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <queue>
#include <cmath>
#include <string>
#include <cstring>
#include <map>
#include <set>
#include <math.h>
#include <unordered_map>
//#include <tr1/unordered_map>
using namespace std;
#define me(x,y) memset(x,y,sizeof x)
#define MIN(x,y) x < y ? x : y
#define MAX(x,y) x > y ? x : y
typedef long long ll;
typedef unsigned long long ull;
const int maxn = 100;
const double INF = 0x3f3f3f3f;
const int MOD = 1e9+7;
const double eps = 1e-06;
const double pi = acos(-1);
struct Matrix
{
int m[maxn][maxn];
};
Matrix Mul(Matrix A,Matrix B,int n){
Matrix tmp;
for(int i = 1; i <= n; ++i){
for(int j = 1; j <= n; ++j){
tmp.m[i][j] = 0;
}
}
for(int i = 1; i <= n; ++i){
for(int j = 1; j <= n; ++j){
for(int k = 1; k <= n; ++k){
tmp.m[i][j] += A.m[i][k]*B.m[k][j];
tmp.m[i][j] %= MOD;
}
}
}
return tmp;
}
Matrix Qpow(Matrix A,int N,int n){ //求A的N次幂
Matrix ans;
for(int i = 1; i <= n; ++i){
for(int j = 1; j <= n; ++j){
if(i == j) ans.m[i][j] = 1;
else ans.m[i][j] = 0;
}
}
while(N){
if(N&1) ans = Mul(ans,A,n);
A = Mul(A,A,n);
N >>=1;
}
return ans;
}
int main() {
int n;
Matrix a;
a.m[1][1]=1,a.m[1][2]=-1;
a.m[2][1]=1,a.m[2][2]=0;
int x,y;
cin>>x>>y;
cin>>n;
if(n == 1){
cout<<(x%MOD+MOD)%MOD<<endl;
return 0;
}
if(n == 2){
cout<<(y%MOD+MOD)%MOD<<endl;
return 0;
}
a = Qpow(a,n-1,2);
cout<<((a.m[2][1]*y%MOD+a.m[2][2]*x%MOD)%MOD+MOD)%MOD<<endl;
return 0;
}
/*
*/