Happy Necklace(矩阵快速幂)

Happy NecklaceLittle

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

思路:
通过规律发现是一个1 * 3的矩阵乘上一个3 * 3的矩阵;
而关系是f(n) = f(n-1)+f(n-3),所以就直接用矩阵快速幂。题目给了两项了,只需通过规律再求一项即可。{3,4,6}乘一个3*3的矩阵,从而求出剩下的项。

完整代码:

#include<iostream>
using namespace std;
typedef long long ll;
const int MOD=1e9+7;
const int maxn=3;
#define mod(x) ((x)%MOD)
struct mat      //矩阵结构体
{
    ll m[maxn][maxn];
}unit;

mat mat_mul(mat a,mat b)     //矩阵乘法
{
    mat ret;
    ll x;
    for(int i=0;i<maxn;i++)
    {
        for(int j=0;j<maxn;j++)
        {
            x=0;
            for(int k=0;k<maxn;k++)
            {
                x+=mod((ll)a.m[i][k]*b.m[k][j]);
            }
            ret.m[i][j]=mod(x);
        }
    }
    return ret;
}

void init_unit()
{
    for(int i=0;i<maxn;i++)
    {
        unit.m[i][i]=1; //单位矩阵
    }
    return ;
}

mat pow_mat(mat a,ll n)     //快速幂
{
    mat ret=unit;
    while(n)
    {
        if(n&1)
        {
            ret=mat_mul(ret,a);
        }
        a=mat_mul(a,a);
        n>>=1;
    }
    return ret;
}

int main()
{
    ll n,t;
    init_unit();
    cin>>t;
    while(t--)
    {
        cin>>n;
        if(n<4)
        {
            cout<<n+1<<endl;
        }
        else if(n==4)       //找出规律算出第四项为6(当然找出规律算第一项也可以)
        {
            cout<<"6"<<endl;
        }
        else
        {
            mat a,b;
            b.m[0][0]=1;b.m[0][1]=1;b.m[0][2]=0;
            b.m[1][0]=0;b.m[1][1]=0;b.m[1][2]=1;
            b.m[2][0]=1;b.m[2][1]=0;b.m[2][2]=0;

            //f(n) = f(n-1)+f(n-3)
            a.m[0][0]=4;a.m[0][1]=3;a.m[0][2]=2;
            b=pow_mat(b,n-4);
            
            //如果数据为1、2、3项,如果用这三项的话,要用第四项求第一项,所以不方便
            /*a.m[0][0]=3;a.m[0][1]=2;a.m[0][2]=1;
            b=pow_mat(b,n-3);*/
            //然后那个else if可以不用写
            
            a=mat_mul(a,b);
            cout<<mod(a.m[0][0])<<endl;
        }
    }
    return 0;
}
发布了60 篇原创文章 · 获赞 69 · 访问量 2834

猜你喜欢

转载自blog.csdn.net/qq_45856289/article/details/104399329