ZOJ Problem Set - 3702 Gibonacci number

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)=1

In 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 forG(1) is a random integer t, (t>=1). Given thei-th Gibonacci number value G(i), and the numberj, 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 contains3 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 fort, output -1.

Sample Input

4
1 1 2
3 5 4
3 4 6
12 17801 19

Sample Output

2
8
-1
516847



題解:

公式推導:

斐波那契數列:                          G波那契:

f(0)=1                                          G(0)=1

f(1)=1                                          G(1)=t

f(2)=2                                          G(2)=1+t

f(3)=3                                          G(3)=1+2t

f(4)=5                                          G(4)=2+3t

f(5)=8                                          G(5)=3+5t

f(6)=13                                        G(6)=5+8t

f(7)=21                                        G(7)=8+13t


由上兩個數列可推得:G(n)=f(n)-f(n-1)+f(n-1)*t

所以:

                     t={ G(n)-[f(n-1)-f(n-1)] } / f(n-1)

注意不能整除和小於等於0的情況(就是在這裏WA裏3次,人艱不拆啊!!!)

還有,不能用int,int會爆掉,舉個極端例子就能發現輸出的數是負的,如 1,1000000,20


代碼:

#include<stdio.h>
using namespace std;
int main()
{
  int T;
  long long f[50],g[50];
  f[0]=1;f[1]=1;g[0]=1;
  for(int i=2;i<=20;i++)f[i]=f[i-1]+f[i-2];
  scanf("%d",&T);
  while(T--)
  {
    int i,j;
    long long z;
    scanf("%d%lld%d",&i,&z,&j);
    g[i]=z;
    long long t=g[i]-(f[i]-f[i-1]);
    if(t%f[i-1]||t<=0)
    {
      printf("-1\n");
      continue;
    }
    t/=f[i-1];
    g[1]=t;
    for(int k=2;k<=j;k++)g[k]=g[k-1]+g[k-2];
    printf("%lld\n",g[j]);
  }
  return 0;
}


方法二:看了12級一個師兄的代碼是用二分暴力過的,數據才20個,1000000也不是很大。     

發佈了41 篇原創文章 · 獲贊 4 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章