Loading

HDU 5950:Recursive sequence(矩阵快速幂)

http://acm.hdu.edu.cn/showproblem.php?pid=5950

题意:给出 a,b,n,递推出 f(n) = f(n-1) + f(n-2) * 2 + n ^ 4. f(1) = a, f(2) = b.

思路:在比赛时候知道是矩阵快速幂,可是推不出矩阵.那个n^4不知道怎么解决。结束后问其他人才知道要构造一个7 * 7的矩阵,而不是3 * 3的..

转自:http://blog.csdn.net/spring371327/article/details/52973534

 1 #include <cstdio>
 2 #include <algorithm>
 3 #include <iostream>
 4 #include <cstring>
 5 #include <string>
 6 #include <cmath>
 7 #include <queue>
 8 #include <vector>
 9 using namespace std;
10 #define N 1010
11 #define INF 0x3f3f3f3f
12 #define MOD 2147493647
13 typedef long long LL;
14 
15 struct matrix
16 {
17     LL a[7][7];
18 
19     void init() {
20         memset(a, 0, sizeof(a));
21         for(int i = 0; i < 7; i++) a[i][i] = 1;
22     }
23 
24     matrix operator * (matrix b) {
25         matrix ans;
26         LL tmp;
27         for(int i = 0; i < 7; i++) {
28             for(int j = 0; j < 7; j++) {
29                 ans.a[i][j] = 0;
30                 for(int k = 0; k < 7; k++) {
31                     tmp = a[i][k] * b.a[k][j] % MOD;
32                     ans.a[i][j] = (ans.a[i][j] + tmp % MOD) % MOD;
33                 }
34             }
35         }
36         return ans;
37     }
38 };
39 
40 matrix q_pow(matrix a, LL b)
41 {
42     matrix ans;
43     ans.init();
44     while(b) {
45         if(b & 1) ans = ans * a;
46         b >>= 1;
47         a = a * a;
48     }
49     return ans;
50 }
51 
52 int main()
53 {
54     matrix mo;
55     memset(mo.a, 0, sizeof(mo.a));
56     mo.a[0][1] = 1;
57     mo.a[1][0] = 2; mo.a[1][1] = 1, mo.a[1][2] = 1, mo.a[1][3] = 4, mo.a[1][4] = 6, mo.a[1][5] = 4, mo.a[1][6] = 1;
58     mo.a[2][2] = 1, mo.a[2][3] = 4, mo.a[2][4] = 6, mo.a[2][5] = 4, mo.a[2][6] = 1;
59     mo.a[3][3] = 1, mo.a[3][4] = 3, mo.a[3][5] = 3, mo.a[3][6] = 1;
60     mo.a[4][4] = 1, mo.a[4][5] = 2, mo.a[4][6] = 1;
61     mo.a[5][5] = 1, mo.a[5][6] = 1;
62     mo.a[6][6] = 1;
63     int t;
64     scanf("%d", &t);
65     while(t--) {
66         long long n, a, b;
67         scanf("%I64d%I64d%I64d", &n, &a, &b);
68         if(n == 1) printf("%I64d\n", a);
69         else if(n == 2) printf("%I64d\n", b);
70         else {
71             matrix ans = q_pow(mo, n - 2);
72             LL sum = 0;
73             sum = (sum + ans.a[1][0] * a) % MOD;
74             sum = (sum + ans.a[1][1] * b) % MOD;
75             sum = (sum + ans.a[1][2] * 16) % MOD;
76             sum = (sum + ans.a[1][3] * 8) % MOD;
77             sum = (sum + ans.a[1][4] * 4) % MOD;
78             sum = (sum + ans.a[1][5] * 2) % MOD;
79             sum = (sum + ans.a[1][6]) % MOD;
80             printf("%I64d\n", sum);
81         }
82     }
83     return 0;
84 }

 

posted @ 2016-10-30 21:29  Shadowdsp  阅读(263)  评论(0编辑  收藏  举报