In mathematical terms, the normal sequence F(n) of Fibonacci numbers is defined by the recurrence relation
F(n)=F(n-1)+F(n-2)with seed values
F(0)=1, F(1)=1In this Gibonacci numbers problem, the sequence G(n) is defined similar
G(n)=G(n-1)+G(n-2)with the seed value for G(0) is 1 for any case, and the seed value for G(1) is a random integer t, (t>=1). Given the i-th Gibonacci number value G(i), and the number j, your task is to output the value for G(j)
Input
There are multiple test cases. The first line of input is an integer T < 10000 indicating the number of test cases. Each test case contains 3 integers i, G(i) and j. 1 <= i,j <=20, G(i)<1000000
Output
For each test case, output the value for G(j). If there is no suitable value for t, output -1.
Sample Input
4 1 1 2 3 5 4 3 4 6 12 17801 19
Sample Output
2 8 -1 516847
题意:给出一个数列的第0项和第i项的值以及i,求第j项的值是多少。其中G(0)=1,G[i] = G[i-1] + G[i-2]。
分析:经过推导可以发现,G[i] = fib[i-2] * G[0] + fib[i-1] * G[1],又因为G[0]=1,所以G[i] = fib[i-2] + fib[i-1] * G[1]其中fib[i]表示斐波那契数列的第i项。所以我们只需要求出G[1],就可以求出G[j]了。注意有些要特判。
#include <iostream> #include <cstdio> #include <cmath> #include <cstdlib> #include <vector> #include <set> #include <map> #include <stack> #include <queue> #include <cstring> #include <string> using namespace std; typedef long long LL; const int N = 1e5 + 10; long long fib[25]; void Init() { // 预处理出斐波那契数列数列的前21项 fib[0] = fib[1] = 1; for(int i = 2; i <= 20; i++) fib[i] = fib[i-1] + fib[i-2]; } int main() { Init(); int T; LL a, n, k; scanf("%d", &T); while(T--) { scanf("%lld%lld%lld", &a, &n, &k); if(a == 1) { // 若G[1]已给出 if(k == 1) printf("%lld\n", n); else { printf("%lld\n", fib[k-2] + fib[k-1] * n); } } else { // G[i] = fib[i-2] + fib[i-1] * G[1] LL p = n - fib[a-2]; if(p % fib[a-1] != 0 || p <= 0) { printf("-1\n"); continue; } else { LL q = p / fib[a-1]; if(k == 1) printf("%lld\n", q); else printf("%lld\n", fib[k-2] + fib[k-1] * q); } } } return 0; }