Recursive sequence
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 2042 Accepted Submission(s): 914
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(1) = a , F(2) = b , F(n) = F(n-1) + F(n-2) * 2 + n^4, 求F(n)
思路:
构造矩阵。
类似斐波那契数矩阵构造
因为有n^4 所以想到要用其得到 (n+1)^4 = n^4 + 4*n^3 + 6*n^2 + 4*n + 1
可知得到(n+1)^4 需要 n^4 , n^3, n^2 , n , 1
得到F(n)则需要F(n-1) F(n-2)和n^4
构造矩阵 A(n^4 n^3 n^2 n 1 F(n-1) F(n-2) )
需另外构造矩阵 B 使得 A*B = ((n+1)^4 (n+1)^3 (n+1)^2 n+1 1 F(n) F(n-1) )
得矩阵B
之后用矩阵快速幂
#include<iostream>
#include<string.h>
#include<stdio.h>
#include<math.h>
using namespace std;
#define LL long long
LL T,N,a,b;
const LL mod = 2147493647;
struct node
{
LL a[10][10],h,l;
node(){
memset(a,0,sizeof a);
}
friend node operator * (node a,node b)
{
node c;
c.h = a.h,c.l = b.l;
for(int i=0;i<a.h;i++){
for(int j=0;j<b.l;j++){
for(int k=0;k<7;k++){
c.a[i][j] += a.a[i][k] * b.a[k][j];
c.a[i][j] %= mod;
}
}
}
return c;
}
};
node A,B;
node jqkm(node a,LL m)
{
node base = a,ans;
for(int i=0;i<7;i++){
ans.a[i][i] = 1;
}
ans.h = ans.l = base.h = base.l = 7;
while(m){
if(m&1) ans = ans*base;
base=base*base;
m>>=1;
}
return ans;
}
int main()
{
scanf("%lld",&T);
LL aa[10][10]={{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,0,0},{1,0,0,0,0,1,2},{0,0,0,0,0,1,0}};
A.h = A.l = 7;
for(int i=0;i<7;i++){
for(int j=0;j<7;j++){
A.a[i][j] = aa[i][j];
}
}
while(T--){
scanf("%lld%lld%lld",&N,&a,&b);
if(N==1){
printf("%lld\n",a%mod);
continue;
}
else if(N==2){
printf("%lld\n",b%mod);
continue;
}
LL bb[10]={81,27,9,3,1,b%mod,a%mod};
for(int i=0;i<7;i++) B.a[i][0] = bb[i];
B.h=7,B.l=1;
node C = jqkm(A, N-2);
B = C*B;
printf("%lld\n",B.a[5][0]);
}
return 0;
}