Happy Necklace
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 863 Accepted Submission(s): 383
phpProblem DescriptionLittle 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 n 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+7.
Note: The necklace is a single string, {not a circle}.
InputThe first line of the input contains an integer T(1≤T≤10000), denoting the number of test cases.
For each test case, there is a single line containing an integer 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+7.
Sample Input2 2 3
Sample Output3 4
Source
求得 A =ios
【AC代碼】app
/* 矩陣快速冪模板 by chsobin */ #include<iostream> #include<cstdio> #include<cstring> using namespace std; typedef long long ll; const int maxn = 3; const ll mod = 1e9 + 7; //矩陣結構體 struct Matrix{ ll a[maxn][maxn]; void init(){ //初始化爲單位矩陣 memset(a, 0, sizeof(a)); for(int i=0;i<maxn;++i){ a[i][i] = 1; } } }; //矩陣乘法 Matrix mul(Matrix a, Matrix b){ Matrix ans; for(int i=0;i<maxn;++i){ for(int j=0;j<maxn;++j){ ans.a[i][j] = 0; for(int k=0;k<maxn;++k){ ans.a[i][j] += a.a[i][k] * b.a[k][j]; ans.a[i][j] %= mod; } } } return ans; } //矩陣快速冪 Matrix qpow(Matrix a, ll n){ Matrix ans; ans.init(); while(n){ if(n&1) ans = mul(ans, a); a = mul(a, a); n /= 2; } return ans; } ////for debug //void output(Matrix a){ // for(int i=0;i<maxn;++i){ // for(int j=0;j<maxn;++j){ // cout << a.a[i][j] << " "; // } // cout << endl; // } //} int main(){ Matrix A = { 1,1,0,0,0,1,1,0,0 }; //遞推矩陣 int t; cin >> t; ll n; int ans[5] = {0, 0, 3, 4, 6}; //枚舉初始狀況 while(t--){ cin >> n; if(n<=4) cout << ans[n] << endl; else{ Matrix m = qpow(A , n-4); ll temp = 6 * m.a[0][0] % mod; temp = (temp + 4 * m.a[1][0]%mod)%mod; temp = (temp + 3 * m.a[2][0]%mod)%mod; cout << temp << endl; } } return 0; }
【總結】:less
看到數據量就明白了這一類題的作法ide
1.打表atom
2.根據打表結果,寫出遞推方程。spa
3.將遞推方程構造爲矩陣。debug
4.快速冪求解。設計