您的位置:首页 > 其它

【递归】普通递归关系(矩阵快速幂)

2016-07-21 14:26 375 查看

题目描述

考虑以下定义在非负整数n上的递归关系:



其中a、b是满足以下两个条件的常数:



给定f0, f1, a, b和 n,请你写一个程序计算F(n),可以假定F(n)是绝对值不超过109的整数(四舍五入)。

输入

输入文件一行依次给出5个数,f0 ,f1,a,b和n,f0,f1是绝对值不超过109 ,n是非负整数,不超过109。另外,a、b是满足上述条件的实数,且|a|,|b|≤106 。

输出

一行,F(n)的值

样例输入

0 1 1 1 20

样例输出

6765


#include <set>
#include <map>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <cctype>
#include <cstdio>
#include <string>
#include <vector>
#include <cassert>
#include <cstdlib>
#include <cstring>
#include <sstream>
#include <iostream>
#include <algorithm>
#define pi acos(-1.0)
#define mod 1000000007
#define inf 1e20
using namespace std;
int line[20],n,sum=0;
int w[1005][1005];
int dp[1005][1005];
struct mat
{
int n,m,a[2][2];
mat(int i=0,int j=0)
{
n=i,m=j;
memset(a,0,sizeof(a));
}
mat operator*(const mat&p)const
{
mat q(n,p.m);
int i,j,k;
for(int i=0; i<n; i++)
for(int j=0; j<m; j++)
for(int k=0; k<m; k++)
q.a[i][k]=(q.a[i][k]+1LL*a[i][j]*p.a[j][k])%mod;
return q;
}
};
int main()
{
int i,j,m,k,t,f0,f1;
long long a,b,n,x;
scanf("%lld%lld%lld%lld%lld",&f0,&f1,&a,&b,&n);
if(n==0)
{
cout<<f0<<endl;
exit(0);
}
if(n==1)
{
cout<<f1<<endl;
exit(0);
}
mat f(1,2);
f.a[0][0]=f1,f.a[0][1]=f0;
mat g(2,2);
g.a[0][0]=a,g.a[0][1]=1,g.a[1][0]=b,g.a[1][1]=0;
n--;
while(n)
{
if(n&1)f=f*g;
g=g*g;
n>>=1;
}
printf("%d\n",f.a[0][0]);
//system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: