B - Fibonacci Sequence URAL - 1133二分还原斐波那契数列

之前所见过的还原斐波那契数列都是数据量比较小的,这次遇到一个数据量比较大的,而且其中的技巧也是第一次见到, 看大神的一波操作,收获还是挺多的;
题中给出斐波那契数列中的两个值fi < fj, 还原这个数列的话, 采用二分的思想, 就是在给定的数据范围之内找到距离fi最近的一个数就可以还原整个数列, 采用二分的思想可以较快的找到满足题中要求的数列;
给出题目:

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: i, Fi, j, Fj, n.
−1000 ≤ i, j, n ≤ 1000, i ≠ j,
−2·10 9 ≤ Fk ≤ 2·10 9 ( k = min( i, j, n), …, max( i, j, n)).
Output
The output consists of a single integer, which is the value of Fn.
Example
input
3 5 -1 4 5
output
12

Notes
In the example you are given: F 3 = 5, F −1 = 4; you asked to find the value of F 5. The following Fibonacci sequence can be reconstructed using known values:
…, F −1 = 4, F 0 = −1, F 1 = 3, F 2 = 2, F 3 = 5, F 4 = 7, F 5 = 12, …
Thus, the answer is: F 5 = 12.

AC代码:

#include <bits/stdc++.h>

using namespace std;
#define INF 0x3f3f3f3f

typedef long long ll;

int main()
{
    ll i, fi, j, fj, n;
    while(cin >> i >> fi >> j >> fj >> n)
    {
        if(i > j)
        {
            swap(i, j);
            swap(fi, fj);
        }
        ll l, r, mid, a, b, c;
        l = -2000000000LL, r = 2000000000LL;
        while(l < r)
        {
            mid = (l + r) / 2;
            a = fi;
            b = mid;
            for(int k = i + 2; k <= j; k++)
            {
                c = a + b;
                a = b;
                b = c;
                if(c > 4000000001LL || c < -4000000001LL)
                    break;
            }
            if(b < fj)
            {
                l = mid + 1;
            }
            else if(b > fj)
            {
                r = mid - 1;
            }
            else
            {
                l = mid, r = mid;
            }
        }
        a = fi;
        b = r;
        if(n >= i + 1)
        {
            for(int k = i + 2; k <= n; k++)
            {
                c = a + b;
                a = b;
                b = c;
            }
            cout << b << endl;
        }
        else
        {
            for(int k = i - 1; k >= n; k--)
            {
                c = b - a;
                b = a;
                a = c;
            }
            cout << a << endl;
        }
    }

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值