ZOJ 3702 Gibonacci number(数学推导题)
Time Limit:?2 Seconds ?????Memory Limit:?65536 KB
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 19Sample 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; }總結
以上是生活随笔為你收集整理的ZOJ 3702 Gibonacci number(数学推导题)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 原创 | 一文了解那些和Spring B
- 下一篇: 过分了!耗资 5600 万、4 年开发的