nefu Not Fibonacci 457 (矩阵连乘)

来源:互联网 发布:c语言窗口程序视频教程 编辑:程序博客网 时间:2024/06/11 15:02

Not Fibonacci

Problem : 457

Time Limit : 1000ms

Memory Limit : 65536K

description

Maybe ACMers of HIT are always fond of fibonacci numbers, because it is so beautiful. Don't you think so? At the same time, fishcanfly always likes to change and this time he thinks about the following series of numbers which you can guess is derived from the definition of fibonacci number. The definition of fibonacci number is: f(0) = 0, f(1) = 1, and for n>=2, f(n) = f(n - 1) + f(n - 2) We define the new series of numbers as below: f(0) = a, f(1) = b, and for n>=2, f(n) = p*f(n - 1) + q*f(n - 2),where p and q are integers. Just like the last time, we are interested in the sum of this series from the s-th element to the e-th element, that is, to calculate S(n)=f(s)+f(s+1)+...+f(e); 

input

The first line of the input file contains a single integer t (1 <= t <= 30), the number of test cases, followed by the input data for each test case. Each test case contains 6 integers a,b,p,q,s,e as concerned above. We know that -1000 <= a,b <= 1000,-10 <= p,q <= 10 and 0 <= s <= e <= 2147483647. 

output

One line for each test case, containing a single interger denoting S MOD (10^7) in the range [0,10^7) and the leading zeros should not be printed. 

sample_input

20 1 1 -1 0 30 1 1 1 2 3

sample_output

23

hint

Hint: You should not use int/long when it comes to an integer bigger than 2147483647. 

source

//题意:

已知f(0)=a,f(1)=b.且有递推关系f(n)=p*f(n-1)+q*f(n-2),n>=2,且定义sum=f(s)+f(s-1)+......f(e-1)+f(e),求sum%10^7的值。

/*
思路:
先用一个s[n]数组存放前n个数的和即:s[n]=f[0]+f[1]+f[2]+......+f[n];
则:sun=s[e]-s[s-1];
由s[n]=s[n-1]+f[n];和f[n]=p*(f[n-1])+q*f[n-2];
可以构造成矩阵为:
 s[n]         1  p  q     s[n-1]
 f[n]    =    0  p  q  *  f[n-1]
 f[n-1]       0  1  0     f[n-2]
将以上矩阵简化可得:
 s[n]         1  p  q  ^(n-1)    s[1]
 f[n]    =    0  p  q     *  f[1]
 f[n-1]       0  1  0       f[0]
由以上结论可得到以下代码:

#include<stdio.h>#include<math.h>#include<string.h>#include<algorithm>#define ll long long#define M 10000000using namespace std;struct mat{ll m[3][3];};mat I={1,0,0,0,1,0,0,0,1};mat multi(mat a,mat b)//两矩阵相乘 {mat c;int i,j,k;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]*b.m[k][j]%M;}c.m[i][j]%=M;}}return c;}mat power(mat a,ll k)//矩阵快速幂 {mat ans=I,p=a;while(k){if(k&1){ans=multi(ans,p);k--;}k>>=1;p=multi(p,p);}return ans;}int main(){int t;mat a;ll x,y,p,q,s,e;scanf("%d",&t);while(t--){scanf("%lld%lld%lld%lld%lld%lld",&x,&y,&p,&q,&s,&e);a.m[0][0]=1;a.m[0][1]=p;a.m[0][2]=q;a.m[1][0]=0;a.m[1][1]=p;a.m[1][2]=q;a.m[2][0]=0;a.m[2][1]=1;a.m[2][2]=0;s--;ll s1,s2;if(s<0) s1=0;else if(s==0) s1=x;else{mat ans=power(a,s-1);s1=(ans.m[0][0]%M*(x+y)%M+ans.m[0][1]%M*y%M+ans.m[0][2]%M*x%M)%M;}if(e==0) s2=x;else{mat ans=power(a,e-1);s2=(ans.m[0][0]%M*(x+y)%M+ans.m[0][1]%M*y%M+ans.m[0][2]%M*x%M)%M;}ll cnt=((s2-s1)%M+M)%M;printf("%lld\n",cnt);}return 0;} 


 

0 0