Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 1999 Accepted Submission(s): 829
题目描述:
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}.
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.
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
由题意能得出只要满足所有的长度为2或3的长度的子串即可
长度为2时,只有3中情况:1 1,1 0,0 1;长度为3时只需要判断在2的情况中接一个字符保证1数目不小于0即可,在1 1的情况后面可跟1或0,变成1 1 1和1 1 0,1 0 和0 1后面都只能跟1,变成了1 0 1和0 1 1。之后的长度i的情况均是看i - 1时的后两位的种类数量情况。长度i的1 1情况总数等于长度i - 1的1 1和0 1这两种情况之和,1 0情况总数等于长度i - 1的1 1情况总数,而0 1情况总数等于i - 1的1 0情况总数。
初始矩阵为(1,1,1)T
相乘矩阵为 {(1,0,1),(1,0,0),(0,1,0)}
代码:
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
#define ll long long
using namespace std;
const int mod = 1e9 + 7;
struct Matrix
{
ll m[3][3];
Matrix()
{
memset(m, 0, sizeof m);
}
};
Matrix pow(Matrix a, Matrix b)
{
Matrix c;
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
{
for(int k = 0; k < 3; k++)
{
c.m[i][j] += a.m[i][k] * b.m[k][j];
c.m[i][j] %= mod;
}
}
}
return c;
}
Matrix pow_matrix(Matrix a, ll n)
{
Matrix b;
b.m[0][0] = b.m[1][0] = b.m[0][2] = b.m[2][1] = 1;
while(n)
{
if(n & 1)
a = pow(b, a);
n>>= 1;
b = pow(b, b);
}
return a;
}
/*void pnt(Matrix a)
{
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
printf("%lld ", a.m[i][j]);
printf("\n");
}
}*/
int main()
{
int T;
scanf("%d", &T);
while(T--)
{
ll n;
scanf("%I64d", &n);
if(n == 2)
printf("3\n");
else
{
Matrix ans;
ans.m[0][0] = ans.m[1][0] = ans.m[2][0] = 1;
ans = pow_matrix(ans, n - 2);
printf("%lld\n", (ans.m[0][0] + ans.m[1][0] + ans.m[2][0]) % mod);
}
}
return 0;
}
本文探讨了LittleQ为女友挑选项链的问题,项链由红蓝珠子组成,需确保任意质数长度的连续子串中红珠不少于蓝珠。通过分析长度为2和3的子串情况,应用矩阵快速幂算法高效求解不同项链数量,答案模10^9+7。
395

被折叠的 条评论
为什么被折叠?



