传送门:点我
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 1E9+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≤10^18), denoting the number of beads on the necklace.OutputFor each test case, print a single line containing a single integer, denoting the answer modulo 1E9+7.Sample Input
2 2 3
Sample Output
3 4
大意是:一个串(不结环)由红色和蓝色珠子组成,要求每素数个串红色的珠子数量大于等于蓝色的,给定串的长度,询问问能构成的串的种类数,mod 1e9+7。
思路:
红用A表示,蓝用B表示
显然当n==2:
有 AB,AA,BA三种情况
记a[n],b[n],c[n]分别为以三种为末尾的字符串的个数
当n==3时:
AB后面可以加A ==> ABA (末尾为BA,下同)
AA后面可以加 A或B ==> AAA,AAB
BA后面可以加A ==> BAA
得到递推式
a[n] = b[n-1]
b[n] = b[n-1]+c[n-1]
c[n] = a[n-1]
记题目所求的个数为p[n]
p[n] = a[n]+b[n]+c[n] = 2*b[n-1]+a[n-1]+c[n-1] = (a[n-1]+b[n-1]+c[n-1]) + b[n-1] = p[n-1] + (b[n-2]+c[n-2]) = p[n-1] + (b[n-3]+c[n-3]+a[n-3]) = p[n-1]+p[n-3]
到此得到递推关系式:p[n] = p[n-1]+p[n-3]
变成矩阵快速幂的模版题了。
代码:
#include <cstdio> #include <cstring> #include <cmath> #include <cstdlib> #include <ctime> #include <iostream> #include <algorithm> #include <sstream> #include <string> #include <vector> #include <queue> #include <stack> #include <map> #include <set> #include <utility> #include <bitset> #define LL long long #define pb push_back #define mk make_pair #define pill pair<int, int> #define mst(a, b) memset(a, b, sizeof a) #define REP(i, x, n) for(int i = x; i <= n; ++i) #define pi acos(-1.0) #define Max_N 1001 #define inf 0x3f3f3f3f #define N 1001 #define ll long long using namespace std; const LL MOD = 1e9+7; struct mat{ LL a[10][10]; }; mat mat_mul(mat x,mat y,int len){ mat res; memset(res.a,0,sizeof(res.a)); for(int i = 0 ; i < len ; i ++){ for(int j = 0 ; j < len ;j ++){ for(int k = 0 ; k < len ;k ++) res.a[i][j] = (res.a[i][j] + (x.a[i][k]*y.a[k][j]*1LL)%MOD)%MOD; } } return res; } mat mat_qpow(mat a,LL b,int len){ mat ans; memset(ans.a,0,sizeof(ans.a)); for(int i = 0 ;i < len ; i ++) ans.a[i][i] = 1LL; while(b){ if(b&1) ans = mat_mul(ans,a,len); a = mat_mul(a,a,len); b>>=1; } return ans; } int main(){ int t; scanf("%d",&t); while(t--) { LL n; scanf("%lld",&n); if(n == 2){ puts("3");continue; } else if(n == 3){ puts("4");continue; } else if(n == 4){ puts("6");continue; } mat b; b.a[0][0] = 1; b.a[0][1] = 0; b.a[0][2] = 1; b.a[1][0] = 1; b.a[1][1] = 0; b.a[1][2] = 0; b.a[2][0] = 0; b.a[2][1] = 1; b.a[2][2] = 0; b = mat_qpow(b,n-4,3); LL ans = (b.a[0][0]*6LL+b.a[0][1]*4LL+b.a[0][2]*3LL)%MOD; cout<<ans<<endl; } return 0; } /* 2 3 4 */