题目链接
Recursive sequence
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 632 Accepted Submission(s): 301
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.
题意:
已知递推公式:F(n) = 2*F(n-2) + F(n-1) + n4
给出F(1) = a,F(2) = b,和一个N,求F(N)等于多少?
题解:
由于N很大,直接递推肯定超时,所以要用到矩阵快速幂的知识log(n)的复杂度来解决。问题的关键就在于如何构造矩阵上,可以看出本题的递推公式是一个非线性的式子,所以要将非线性的部分展开为线性的。
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<vector>
#include<queue>
#include<stack>
using namespace std;
#define rep(i,a,n) for (int i=a;i<n;i++)
#define per(i,a,n) for (int i=n-1;i>=a;i--)
#define pb push_back
#define fi first
#define se second
typedef vector<int> VI;
typedef long long ll;
typedef pair<int,int> PII;
const int inf=0x3fffffff;
const ll mod=2147493647;
const int maxn=7;
struct matrix
{
ll a[maxn][maxn];
matrix operator *(matrix b)
{
matrix c;
for(int i=0;i<maxn;i++)
{
for(int j=0;j<maxn;j++)
{
c.a[i][j]=0;
for(int k=0;k<maxn;k++)
c.a[i][j]=(c.a[i][j]+a[i][k]*b.a[k][j]%mod)%mod;
}
}
return c;
}
void init()
{
memset(a,0,sizeof(a));
rep(i,0,maxn) a[i][i]=1;
}
};
matrix p={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};
matrix pow(ll x)
{
matrix ans,tmp=p;
ans.init();
while(x)
{
if(x&1) ans=ans*tmp;
tmp=tmp*tmp;
x/=2;
}
return ans;
}
int main()
{
int cas;
scanf("%d",&cas);
while(cas--)
{
int n;
ll a,b;
scanf("%d",&n);
scanf("%lld%lld",&a,&b);
if(n==1) printf("%lld\n",a);
else if(n==2) printf("%lld\n",b);
else
{
matrix ans=pow(n-2);
ll res=ans.a[0][0]*b+ans.a[0][1]*a+ans.a[0][2]*16+ans.a[0][3]*8+ans.a[0][4]*4+ans.a[0][5]*2+ans.a[0][6];
res=res%mod;
printf("%lld\n",res);
}
}
return 0;
}