简单矩阵连乘。
解法一:s(n)=f[n+2]-f[2];
#include <cstdio>
#include <iostream>
using namespace std;
const int mod=1000000000;
typedef struct
{
long long m[2][2];
}matrix;
matrix P={1,1,1,0};
matrix I={1,0,0,1};
matrix mul(matrix a,matrix b)
{
int i,j,k;
matrix c;
for(i=0;i<2;i++)
for(j=0;j<2;j++)
{
c.m[i][j]=0;
for(k=0;k<2;k++)
c.m[i][j]+=((a.m[i][k]%mod)*(b.m[k][j])%mod)%mod;
c.m[i][j]%=mod;
}
return c;
}
matrix quick_mod(long long n)
{
matrix a=P,b=I;
while(n>0)
{
if(n&1)
b=mul(b,a);
n=n>>1;
a=mul(a,a);
}
return b;
}
int main()
{
int a,b;
long long ans;
while(scanf("%d%d",&a,&b))
{
if(a==0&&b==0) break;
matrix temp1,temp2;
temp1=quick_mod(a);
temp2=quick_mod(b+1);
long long head=(temp1.m[0][0]+temp1.m[0][1])%mod;
long long tail=(temp2.m[0][0]+temp2.m[0][1])%mod;
ans=(tail-head)%mod;
if(ans<0) ans=(ans+mod)%mod;//就是少了这个if语句...WA了10多次...都是泪啊....
printf("%lld\n",ans);
}
return 0;
}
解法二(也是我比较喜欢的):直接构造出含s(n)的矩阵 (只是对于这道题有点麻烦,因为边界太麻烦了)
#include <cstdio>
#include <iostream>
using namespace std;
const int mod=1000000000;
typedef struct
{
long long m[3][3];
}matrix;
matrix P={1,1,1,
0,1,1,
0,1,0};
matrix I={1,0,0,
0,1,0,
0,0,1};
matrix mul(matrix a,matrix b)
{
int i,j,k;
matrix c;
for(i=0;i<3;i++)
for(j=0;j<3;j++)
{
c.m[i][j]=0;
for(k=0;k<3;k++)
c.m[i][j]+=((a.m[i][k]%mod)*(b.m[k][j]%mod))%mod;
c.m[i][j]%=mod;
}
return c;
}
matrix quick_mod(int n)
{
matrix a=P,b=I;
while(n>=1)
{
if(n&1)
b=mul(b,a);
n=n>>1;
a=mul(a,a);
}
return b;
}
int main()
{
int a,b;
int ans;
while(scanf("%d%d",&a,&b))
{
if(a==0&&b==0) break;
if(a==0&&b==1) ans=2;
else if(a==0&&b>=2)
{
matrix temp2=quick_mod(b-1);
ans=((temp2.m[0][0]*2)%mod+(temp2.m[0][1]+temp2.m[0][2])%mod)%mod;
}
else if(a==1&&b==1) ans=1;
else if(a==1&&b>1)
{
matrix temp2=quick_mod(b-1);
ans=((temp2.m[0][0]*2)%mod+(temp2.m[0][1]+temp2.m[0][2])%mod-1)%mod;
}
else
{
int head,tail;
matrix temp1,temp2;
temp1=quick_mod(a-1);
temp2=quick_mod(b-1);
head=((temp1.m[0][0]*2)%mod+(temp1.m[0][1]+temp1.m[0][2])%mod)%mod;
tail=((temp2.m[0][0]*2)%mod+(temp2.m[0][1]+temp2.m[0][2])%mod)%mod;
ans=((tail-head)%mod+(temp1.m[1][1]+temp1.m[1][2])%mod)%mod;
}
if(ans<0) ans=(ans+mod)%mod;
printf("%d\n",ans);
}
return 0;
}