传送门:http://acm.split.hdu.edu.cn/showproblem.php?pid=5950
描述:
Recursive sequence
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 44 Accepted Submission(s): 29
Each case contains only one line with three numbers N, a and b where N,a,b < as described above.
2 3 1 2 4 1 10
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) = f(n−1)+2f∗(n−2)+n4 ,其中 f(1)=a,f(2)=b
思路:
构造矩阵:
(n+1)4 = n4+4n3+6n2+4n+1
所以光
(n+1)4
这个矩阵就能构造出
5∗5
的一个矩阵来, 然后
f(n)=f(n−1)+2∗f(n−2)
这个是
2∗2
的矩阵,所以构造出来就应该是
7∗7
的转移矩阵
A
,递推式为:
不断迭代得:
其中A = {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;
#define ll __int64
const ll M = 2147493647;
const int MAX = 7;
struct Matrix{
ll v[MAX][MAX];
void init(){
memset(v, 0, sizeof(v));
for(int i=0; i<MAX; i++)
v[i][i] = 1;
}
};
//构造的矩阵
Matrix mat = {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 mtMul(Matrix A, Matrix B){ // 求矩阵 A * B
int i, j, k;
Matrix C;
for(i = 0; i < MAX; i ++)
for(j = 0; j < MAX; j ++){
C.v[i][j] = 0;
for(k = 0; k < MAX; k ++){
C.v[i][j] = (A.v[i][k] * B.v[k][j] % M+ C.v[i][j]) % M;
}
}
return C;
}
Matrix mtPow(Matrix A, ll k){ // 求矩阵 A ^ k
if(k == 0) {
memset(A.v, 0, sizeof(A.v));
for(int i = 0; i < MAX; i ++){
A.v[i][i] = 1;
}
return A;
}
if(k == 1) return A;
Matrix C = mtPow(A, k / 2);
if(k % 2 == 0) {
return mtMul(C, C);
}
else {
return mtMul(mtMul(C, C), A);
}
}
int main(){
int T;
scanf("%d", &T);
while(T--){
ll N, a, b;
scanf("%I64d%I64d%I64d", &N, &a, &b);
if(N == 1){
printf("%I64d\n", a);
continue;
}
if(N == 2){
printf("%I64d\n", b);
continue;
}
Matrix tmp = mtPow(mat, N - 2);
ll ans = b * tmp.v[0][0] % M;
ans = (ans + a * tmp.v[0][1] % M) % M;
ans = (ans + 16 * tmp.v[0][2] % M) % M;
ans = (ans + 8 * tmp.v[0][3] % M) % M;
ans = (ans + 4 * tmp.v[0][4] % M) % M;
ans = (ans + 2 * tmp.v[0][5] % M) % M;
ans = (ans + tmp.v[0][6]) % M;
printf("%I64d\n", ans);
}
return 0;
}
代码2:http://paste.ubuntu.com/24540769/