Fibonacci sequence

1133. Fibonacci Sequence

Time Limit: 1.0 second
Memory Limit: 16 MB
is an infinite sequence of integers that satisfies to Fibonacci condition F i + 2 =  F i + 1 +  Fi for any integer  i. Write a program, which calculates the value of  Fn for the given values of  Fi and  Fj.

Input

The input contains five integers in the following order:  iFijFjn.
−1000 ≤  ijn ≤ 1000,  i ≠  j,
−2·10 9 ≤  Fk ≤ 2·10 9 ( k = min( ijn), …, max( ijn)).

Output

The output consists of a single integer, which is the value of  Fn.
 
 
这题目最开始想到的解法是用搜索,由输入的Fi,Fj,求出与Fi相邻的另一个数Fj+1,再往后继续求,加上动态规划的话,复杂度也不算高。。。
但。。。就在准备动手搞的时候,意外发生了。我忽然觉得,或许可以数学方式来递推一下,于是,拿过纸笔在黄纸上算啊算啊。。。
一直没搞出来,算了,还是笨方法吧。
现在的做法就是直接搜索:
 
F(n) = F(n-1)+F(n-2)
现在输入是Fi,Fj,假设i < j.
现在我需要找到F(i+1).
 
很显然,对于任意的k > i.
 
Fk = xFi + yF(i+1).
 
只要求出x,y,问题就解决了。
 
要求出x,y,我只要求F(k-1),F(k-2)的x,y.
 
对了,这个需要做高精度的处理,x,y可能会很大很大。。。
 
 
    static BigInt sx,sy;

    static BigInt sx2,sy2;

    static bool found[N];

    static BigInt value[N][2];

    static const int HALF = 1000;



    static void GetXY(int i,int k,BigInt& x,BigInt& y)

    {

        if(k == i)

        {

            y = 0;

            x = 1;

            return ;

        }



        if(k == i+1)

        {

            x = 0;

            y = 1;

            return ;

        }



        int index =  n + HALFT;



        if(found[index])

        {

            x  = value[index][0];

            y  = value[index][1];

            return;

        }





        GetNext(i,k-1,sx,sy);



        GetNext(i,k-2,sx2,sy2);



        x  = sx+sx2;

        y  = sy+sy2;



        value[index][0] = x;

        value[index][1] = y;

        found[index] = true;

        return;

    }


int GetNextValue(int i,int fi,int j,int fj)

{

   BigInt x,y;

   GetXY(i,j,x,y);

   return (fj - fi*x)/y;

}
 
      

 

 

 

 
 
 

你可能感兴趣的:(fibonacci)