zoukankan      html  css  js  c++  java
  • Fibonacci sequence

    1133. Fibonacci Sequence

    Time Limit: 1.0 second
    Memory Limit: 16 MB
    Problem illustration
    is an infinite sequence of integers that satisfies to Fibonacci conditionFi + 2 = Fi + 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·109 ≤ Fk ≤ 2·109 (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;
    }
    
    
    
     
     
     
     
  • 相关阅读:
    RIO包 健壮的I/O函数代码
    Upgrading WebLogic Application Environments --官方文档
    JAVA的静态代理与动态代理比较--转载
    指向函数的指针--转
    c之指针与数组(1)
    weblogic 异常常见处理方法
    Redis: under the hood---转载
    A GDB Tutorial with Examples--转
    The best career advice I’ve received --转载
    redis 大数据插入
  • 原文地址:https://www.cnblogs.com/catch/p/2878225.html
Copyright © 2011-2022 走看看