Another kind of Fibonacci
Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 1944 Accepted Submission(s): 747
Problem Description
As we all known , the Fibonacci series : F(0) = 1, F(1) = 1, F(N) = F(N - 1) + F(N - 2) (N >= 2).Now we define another kind of Fibonacci : A(0) = 1 , A(1) = 1 , A(N) = X * A(N - 1) + Y * A(N - 2) (N >= 2).And we want to Calculate S(N) , S(N) = A(0)
2 +A(1)
2+……+A(n)
2.
Input
There are several test cases.
Each test case will contain three integers , N, X , Y .
N : 2<= N <= 2 31 – 1
X : 2<= X <= 2 31– 1
Y : 2<= Y <= 2 31 – 1
Each test case will contain three integers , N, X , Y .
N : 2<= N <= 2 31 – 1
X : 2<= X <= 2 31– 1
Y : 2<= Y <= 2 31 – 1
Output
For each test case , output the answer of S(n).If the answer is too big , divide it by 10007 and give me the reminder.
Sample Input
2 1 1 3 2 3
Sample Output
6 196
Author
wyb
Source
HDOJ Monthly Contest – 2010.02.06
/*
真心不好构造{S(n-2), a(n-1)^2,a(n-1)*a(n-2),a(n-2)^2},刚好可以a(n)*a(n-1)=a(n-1)(X*a(n-1)+Y*a(n-2))还有点坑,注意x,y提前取一下模,否则会溢出
加油!!!
Time:2015-4-14 21:22
*/
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long LL;
const int mod=10007;
struct Matrix{
LL mat[5][5];
int n;
void Init(int _n){
n=_n;
memset(mat,0,sizeof(mat));
}
Matrix operator *(const Matrix &b) const{
Matrix ret;
ret.Init(n);
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
for(int k=0;k<n;k++){
ret.mat[i][j]+=mat[i][k]*b.mat[k][j];
ret.mat[i][j]%=mod;
}
}
}
return ret;
}
};
Matrix mat_pow(Matrix a,int k){
Matrix ret;ret.Init(a.n);
for(int i=0;i<ret.n;i++)ret.mat[i][i]=1;
while(k>0){
if(k&1) ret=ret*a;
a=a*a;
k>>=1;
}
return ret;
}
int main(){
int n,x,y;
Matrix trans,ret;
while(scanf("%d%d%d",&n,&x,&y)!=EOF){
trans.Init(4);ret.Init(4);
x%=mod; y%=mod;
trans.mat[0][0]=1; trans.mat[1][0]=1;
trans.mat[1][1]=x*x%mod; trans.mat[2][1]=2*x*y%mod; trans.mat[3][1]=y*y%mod;
trans.mat[1][2]=x; trans.mat[2][2]=y; trans.mat[1][3]=1;
ret.mat[0][0]=1;//s0
ret.mat[0][1]=1;//a1^2
ret.mat[0][2]=1;//a1*a0
ret.mat[0][3]=1;//a0^2
trans=mat_pow(trans,n);
ret=ret*trans;
printf("%d\n",ret.mat[0][0]);
/*
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
printf("%d ",trans.mat[i][j]);
}puts("");
}
*/
}
return 0;
}