hdu 3306 Another kind of Fibonacci

来源:互联网 发布:商务智能与数据挖掘 编辑:程序博客网 时间:2024/05/12 11:12


Another kind of Fibonacci

Time Limit: 3000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 1513    Accepted Submission(s): 577


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 <= 231 – 1
X : 2<= X <= 231– 1
Y : 2<= Y <= 231 – 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
6196
 

Author
wyb
 

Source
HDOJ Monthly Contest – 2010.02.06

该题为矩阵连乘问题,主要考虑以下公式:

 

f(n)=x*f(n-1)+y*f(n-2)


先看 s(n)=s(n-1)+f(n)^2;

所以:s(n-1)=s(n-2)+f(n-1)^2;  右边有2项,s(n-2)和f(n-1)^2必须要有了

  S(n-2)-----------às(n-1)

   F(n-1)^2------à f(n)^2=[xf(n-1)+yf(n-2)]^2=出现了f(n-2)^2和2xyf(n-1)f(n-2),所以共4项

 

最左边是1个空的矩阵(4*4),也是我们要构造的矩阵(只要学过矩阵的人,就能把它算出来了吧)

 


借鉴一下老师的题解 ~=W=


代码:

#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>#include<map>#define mod 10007using namespace std;typedef long long ll;struct matrix{    int mat[4][4];}M,a,unit;matrix operator*(matrix a,matrix b){    matrix temp;    for (int i=0;i<4;++i)        for (int j=0;j<4;++j)        {            int sum=0;            for (int k=0;k<4;++k)                sum=(sum+a.mat[i][k]*b.mat[k][j])%mod;            temp.mat[i][j]=sum;        }        return temp;}//矩阵乘法matrix pow(matrix a,int n){    matrix r=unit;    while(n)    {        if(n&1) r=r*a;        a=a*a;        n>>=1;    }    return r;}//矩阵连乘void init(int x,int y){    x%=mod;y%=mod;    memset(M.mat,0,sizeof(M.mat));    M.mat[0][0]=M.mat[2][1]=1;    M.mat[0][1]=M.mat[1][1]=(x*x)%mod;    M.mat[0][2]=M.mat[1][2]=(y*y)%mod;    M.mat[0][3]=M.mat[1][3]=(2*x*y)%mod;    M.mat[3][1]=x;    M.mat[3][3]=y;}int  main(){    int n,x,y;    memset(unit.mat,0,sizeof(unit.mat));    for(int i=0;i<4;i++)       unit.mat[i][i]=1;    while(~scanf("%d%d%d",&n,&x,&y))    {        init(x,y);        matrix r=pow(M,n-1);        //cout<<r.mat[0][0]<<' '<<r.mat[0][1]<<' '<<r.mat[0][2]<<' '<<r.mat[0][3]<<' ';        int sum=0;        for(int i=0;i<4;i++)           {               sum=(sum+r.mat[0][i])%mod;               //cout<<sum<<endl;           }      printf("%d\n",(sum+1)%mod);    }    return 0;}



0 0
原创粉丝点击