ural 1133. Fibonacci Sequence

1133. Fibonacci Sequence

Time limit: 1.0 second
Memory limit: 64 MB
 

Problem illustration

is an infinite sequence of integers that satisfies to Fibonacci condition Fi + 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: i, Fi, j, Fj, n.
−1000 ≤ i, j, n ≤ 1000, i ≠ j,
−2·109Fk ≤ 2·109 (k = min(i, j, n), …, max(i, j, n)).

Output

The output consists of a single integer, which is the value of Fn.

Sample

inputoutput
3 5 -1 4 5
12

Notes

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

Problem Source: Quarterfinal, Central region of Russia, Rybinsk, October 17-18 2001

思路:由于打表爆了, 采用了别人的二分方法。。

假设 i < j

我们可以二分fi+1,判断是否正确。。

最后我们就知道了fi, fi+1, 就可以算fk了吧

#include <cstdio>
#include <iostream>
using namespace std;
int a, b, k;
long long n, m;
const long long INF = 4e11;
int main() {
    scanf("%d%I64d%d%I64d%d", &a, &n, &b, &m, &k);
    if(a > b) {
        swap(a, b);
        swap(m, n);
    }
    long long l = -INF, r = INF, rt;
    while(l <= r) {
        long long mid = (l+r)>>1;
        long long f0 = n, f1 = mid, f3;
        for(int i = a+2; i <= b; i++) {
            f3 = f0 + f1;
            f0 = f1, f1 = f3;
            if(f1 > INF || f1 < -INF) break;
        }
        if(f1 == m) {
            rt = mid;
            break;
        }
        else if(f1 > m) r = mid - 1;
        else l = mid+1;
    }
    long long f0 = n, f1 = rt,f2 = r;
    if(k >= a+1) {
        for(int i = a+2; i <= k; i++) {
            f2 = f1 + f0;
            f0 = f1, f1 = f2;
        }
        printf("%I64d\n", f1);
    } else {
        for(int i = a-1; i >= k; i--) {
            f2 = f1 - f0;
            f1 = f0, f0 = f2;
        }
        printf("%I64d\n", f0);
    }
    return 0;
}

 

posted on 2016-09-21 14:31  disppr  阅读(162)  评论(0编辑  收藏  举报