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
思路:递推出Gn和G0,G1相关式子:
G0=1;
G1=t;
G2=G1+G0;
G3=2*G1+G0;
G4=3*G1+2*G0;
G5=5*G1+3*G0;
则不难推出,Gi=F【i-1】*t+F【i-2】*1
如果t是正整数的话,辣么就有符合的条件,并且t=(Gi-F【i-2】*1)/F【i-1】;
如果t不是正整数的话,了么就没有符合条件,输出-1.
坑点:如果t==0的时候,也属于没有符合条件,因为题中给出t的范围是大于等于1了~
AC代码:
#include<stdio.h>
#include<string.h>
#include<math.h>
using namespace std;
#define ll long long int
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
ll f[25];
ll g[25];
f[0]=1;
f[1]=1;
for(int i=2;i<=25;i++)
{
f[i]=f[i-1]+f[i-2];
}
memset(g,0,sizeof(g));
int i,gi,j;
ll t;
scanf("%d%d%d",&i,&gi,&j);
int flag=0;
if(i==1)
{
t=gi;
flag=1;
}
else
{
if(((gi-f[i-2])%f[i-1])==0)
t=(gi-f[i-2])/f[i-1],flag=1;
else flag=0;
}
if(flag==0||t<1)
{
printf("-1\n");continue;
}
g[0]=1;
g[1]=t;
for(int k=2;k<=25;k++)
{
g[k]=g[k-1]+g[k-2];
}
printf("%lld\n",g[j]);
}
}