HDU6030 Happy Necklace

Little Q wants to buy a necklace for his girlfriend. Necklaces are single strings composed of multiple red and blue beads. 
Little Q desperately wants to impress his girlfriend, he knows that she will like the necklace only if for every prime length continuous subsequence in the necklace, the number of red beads is not less than the number of blue beads. 
Now Little Q wants to buy a necklace with exactly nn beads. He wants to know the number of different necklaces that can make his girlfriend happy. Please write a program to help Little Q. Since the answer may be very large, please print the answer modulo 109+7109+7. 
Note: The necklace is a single string, {not a circle}.

InputThe first line of the input contains an integer T(1T10000)T(1≤T≤10000), denoting the number of test cases. 
For each test case, there is a single line containing an integer n(2n1018)n(2≤n≤1018), denoting the number of beads on the necklace.
OutputFor each test case, print a single line containing a single integer, denoting the answer modulo 109+7109+7.Sample Input

2
2
3

Sample Output

3
4

矩阵快速幂

题意:长度为n的串,对每一段长度为素数的子串,都满足红色不少于蓝色
其实就是 长度为2和3的子串 红色 不少于 蓝色
所以只要管最后两个的颜色就好,0代表蓝 红代表1
01 可以转移 到 011,末尾变为 11
10 可以转移 到 101,末尾变为 01
11 可以转移 到 110,末尾变为 10,
11也可以转移 到 111,末尾变为 11
所以有初始 答案矩阵 1 1 1
01 关系矩阵 0 0 1
10     1 0 0
11      0 1 1

 1 #include <bits/stdc++.h>
 2 #define mod 1000000007
 3 #define N 3
 4 using namespace std;
 5 typedef long long ll;
 6 ll T,n;
 7 struct Mat{
 8     ll a[N][N];
 9     Mat(){
10         memset(a,0,sizeof(a));
11     }
12 };
13 
14 Mat operator *(Mat A,Mat B){
15     Mat ret;
16     for (int i = 0;i < N;++i){
17         for (int j = 0;j < N;++j){
18             ll tmp = 0;
19             for (int k = 0;k < N;++k){
20                 tmp = (tmp + A.a[i][k]*B.a[k][j]) % mod;
21             }
22             ret.a[i][j] = tmp;
23         }
24     }
25     return ret;
26 }
27 
28 Mat operator ^ (Mat A,ll n){
29     Mat ret;
30     for (int i = 0;i < N;++i) ret.a[i][i] = 1;
31     while(n){
32         if (n&1) ret = ret * A;
33         n >>= 1;
34         A = A*A;
35     }
36     return ret;
37 }
38 
39 int main(){
40     scanf("%lld",&T);
41     while(T--){
42         scanf("%lld",&n);
43         if (n == 2) {
44             puts("3");
45             continue;
46         }
47         Mat A;
48         A.a[0][1] = A.a[1][2] = A.a[2][0] = A.a[2][2] = 1;
49         A = A ^ (n-2);
50         ll ans = 0;
51         for (int i = 0;i < N;++i){
52             for (int j = 0;j < N;++j){
53                 ans = (ans + A.a[i][j]) % mod;
54             }
55         }
56         printf("%lld\n",ans);
57     }
58 }

 

posted @ 2019-02-20 15:35  mizersy  阅读(231)  评论(0编辑  收藏  举报