http://acm.hdu.edu.cn/showproblem.php?pid=5950
Recursive sequence
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 329 Accepted Submission(s): 183
Problem Description
Farmer John likes to play mathematics games with his N cows. Recently, they are attracted by recursive sequences. In each turn, the cows would stand in a line, while John writes two positive numbers a and b on a blackboard. And then, the cows would say their identity number one by one. The first cow says the first number a and the second says the second number b. After that, the i-th cow says the sum of twice the (i-2)-th number, the (i-1)-th number, and
i4
. Now, you need to write a program to calculate the number of the N-th cow in order to check if John’s cows can make it right.
Input
The first line of input contains an integer t, the number of test cases. t test cases follow.
Each case contains only one line with three numbers N, a and b where N,a,b < 231 as described above.
Each case contains only one line with three numbers N, a and b where N,a,b < 231 as described above.
Output
For each test case, output the number of the N-th cow. This number might be very large, so you need to output it modulo 2147493647.
Sample Input
2 3 1 2 4 1 10
Sample Output
85 369HintIn the first case, the third number is 85 = 2*1十2十3^4. In the second case, the third number is 93 = 2*1十1*10十3^4 and the fourth number is 369 = 2 * 10 十 93 十 4^4.
Source
已知f(n) = f(n-1) + 2*f(n-2) + n^4,给你f(1) = a , f(2) = b,以及n;求f(n)%mod;
以前不会这种有次方的矩阵快速幂,还以为可以化简找到什么公式,看了别人的解法才懂,原来也不难。
把f(n)等于啥写出来,再把f(n+1)写出来,再构造矩阵去套就行了。
|1 2 1 4 6 4 1|
|1 0 0 0 0 0 0|
|0 0 1 4 6 4 1|
|0 0 0 1 3 3 1|
|0 0 0 0 1 2 1|
|0 0 0 0 0 1 1|
|0 0 0 0 0 0 1|
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
LL mod=2147493647;
struct Mat{
LL mat[10][10];
Mat()
{
memset(mat,0,sizeof(mat));
}
};
Mat ec(Mat a,Mat b)
{
Mat c;
for(int i=0;i<7;i++)
{
for(int k=0;k<7;k++)
{
for(int j=0;j<7;j++)
{
c.mat[i][j]=(c.mat[i][j]+(a.mat[i][k]*b.mat[k][j])%mod)%mod;
}
}
}
return c;
}
Mat ex(Mat a,LL b)
{
Mat c;
for(int i=0;i<7;i++)
{
c.mat[i][i]=1;
}
while(b)
{
if(b%2==1)
{
c=ec(c,a);
}
b=b/2;
a=ec(a,a);
}
return c;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
LL n,a,b;
scanf("%lld%lld%lld",&n,&a,&b);
if(n==1)
{
printf("%lld\n",a);
continue;
}
if(n==2)
{
printf("%lld\n",b);
continue;
}
Mat c;
c.mat[0][0]=1;c.mat[0][1]=2;c.mat[0][2]=1;c.mat[0][3]=4;c.mat[0][4]=6;c.mat[0][5]=4;c.mat[0][6]=1;
c.mat[1][0]=1;
c.mat[2][2]=1;c.mat[2][3]=4;c.mat[2][4]=6;c.mat[2][5]=4;c.mat[2][6]=1;
c.mat[3][3]=1;c.mat[3][4]=3;c.mat[3][5]=3;c.mat[3][6]=1;
c.mat[4][4]=1;c.mat[4][5]=2;c.mat[4][6]=1;
c.mat[5][5]=1;c.mat[5][6]=1;
c.mat[6][6]=1;
Mat d;
d.mat[0][0]=b;
d.mat[1][0]=a;
d.mat[2][0]=16LL;
d.mat[3][0]=8LL;
d.mat[4][0]=4LL;
d.mat[5][0]=2LL;
d.mat[6][0]=1LL;
Mat e=ex(c,n-2);
e=ec(e,d);
printf("%lld\n",e.mat[0][0]%mod);
}
return 0;
}