Happy Necklace
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)Total Submission(s): 253 Accepted Submission(s): 99
Problem Description
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 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}.
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}.
Input
The 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.
For each test case, there is a single line containing an integer n(2≤n≤1018) , denoting the number of beads on the necklace.
Output
For each test case, print a single line containing a single integer, denoting the answer modulo
109+7
.
Sample Input
2 2 3
Sample Output
3 4
Source
递推式推出来 然后矩阵快速幂搞一搞
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#include <cmath>
#include <cstdlib>
typedef long long ll;
const int N = 0;
const int SIZE = 3;
int l, MOD=1e9+7;
struct Mat{
ll v[SIZE][SIZE]; // value of matrix
Mat() {
memset(v, 0, sizeof(v));
}
};
Mat operator * (Mat a, Mat b) {
Mat c;
for(int i=0;i<SIZE;i++) {
for(int j=0;j<SIZE;j++) {
c.v[i][j] = 0;
for(int k=0;k<SIZE;k++){
c.v[i][j] += (a.v[i][k] * b.v[k][j]) % MOD;
c.v[i][j] %= MOD;
}
}
}
return c;
}
Mat mul(Mat a,ll k ){
Mat tmp;
int i;
for(i=0;i<SIZE;i++){
tmp.v[i][i]=1;
}
while(k){
if(k&1){
tmp=(tmp*a);
}
a=a*a;
k>>=1;
}
return tmp;
}
int main() {
int t;
scanf("%d",&t);
while (t--){
Mat a, b, c;
// a
a.v[0][0] = 4;
a.v[1][0] = 3;
a.v[2][0] = 2;
// b
b.v[0][0] = b.v[0][2]=b.v[1][0]=b.v[2][1]=1;
//初始化地推矩阵
ll n;
scanf("%lld",&n);
if(n==2){
printf("3\n");
}
else if(n==3){
printf("4\n");
}
else {
c=mul(b,n-3);
c=c*a;
printf("%lld\n",c.v[0][0]);
}
}
return 0;
}