递推求值

                             递推求值

                                    
                                      时间限制:1000 ms  |  内存限制:65535 KB
                                     
                                                                 难度:4
描述

给你一个递推公式:

f(x)=a*f(x-2)+b*f(x-1)+c

并给你f(1),f(2)的值,请求出f(n)的值,由于f(n)的值可能过大,求出f(n)对1000007取模后的值。

注意:-1对3取模后等于2

输入
第一行是一个整数T,表示测试数据的组数(T<=10000)
随后每行有六个整数,分别表示f(1),f(2),a,b,c,n的值。
其中0<=f(1),f(2)<100,-100<=a,b,c<=100,1<=n<=100000000 (10^9)
输出
输出f(n)对1000007取模后的值
样例输入
2
1 1 1 1 0 5
1 1 -1 -10 -100 3
样例输出
5
999896



#include<iostream>
#include<cstring>
using namespace std;
typedef long long LL;
const LL maxn=1000007;
struct M
{
	LL matr[3][3];
	M(){memset(matr,0,sizeof(matr));	}
};
M operator * (M a,M b)
{
	M ans;
	for(int i=0;i<3;i++)
		for(int j=0;j<3;j++)
			for(int k=0;k<3;k++)
			{
				ans.matr[i][j]=ans.matr[i][j]+a.matr[i][k]*b.matr[k][j]%maxn;
				ans.matr[i][j]=(ans.matr[i][j]+maxn)%maxn;
			}
	return ans; 
}
M fast(M m,LL n)
{
	M ans;
	for(int i=0;i<3;i++)
	ans.matr[i][i]=1;
	while(n)
	{
		if(n&1)ans=ans*m;
		m=m*m;
		n>>=1;
	}
	return ans;
}
int main()
{
	LL t;
	cin>>t;
	while(t--)
	{
		LL f1,f2,a,b,c,n;
		cin>>f1>>f2>>a>>b>>c>>n;
		if(n==1)cout<<f1<<endl;
		else if(n==2)cout<<f2<<endl;
		else
		{
			M m;
			m.matr[0][0]=b;m.matr[0][1]=a;m.matr[0][2]=1;
			m.matr[1][0]=1;m.matr[2][2]=1;
			m=fast(m,n-2);
			LL ans=(m.matr[0][0]*f2+m.matr[0][1]*f1+m.matr[0][2]*c)%maxn;
			cout<<(ans+maxn)%maxn<<endl;			
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值