之前所见过的还原斐波那契数列都是数据量比较小的,这次遇到一个数据量比较大的,而且其中的技巧也是第一次见到, 看大神的一波操作,收获还是挺多的;
题中给出斐波那契数列中的两个值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;
}