快速幂(2)

链接:https://ac.nowcoder.com/acm/contest/221/C
来源:牛客网

令f(n)=2*f(n-1)+3*f(n-2)+n,f(1)=1,f(2)=2
令g(n)=g(n-1)+f(n)+n*n,g(1)=2
告诉你n,输出g(n)的结果,结果对1e9+7取模

输入描述:

多组输入,每行一个整数n(1<=n<=1e9),如果输入为0,停止程序。

输出描述:

在一行中输出对应g(n)的值,结果对1e9+7取模。

示例1

输入

复制
1
5
9
456
0

输出

复制
2
193
11956
634021561

说明

多组输入,输入为0时,终止程序

备注:

项数极大,朴素算法无法在规定时间内得出结果


PS:快速幂的一般形式为B`=A^N*B(其中B`和B的形式是一样的,只是下标相差1)

B`和B、A都是n阶方阵


 
#include <iostream>
#include<string.h>
#include<stdio.h>
#define ll long long
using namespace std;
const ll mod = 1000000007;
struct mat
{
    ll m[6][6];
    mat()
    {
        memset(m, 0, sizeof(m));
    }
};
mat mul(mat &A, mat &B)
{
    mat C;
    for (int i = 0; i < 6; i++)
    {
        for (int j = 0; j < 6; j++)
        {
            for (int k = 0; k < 6; k++) 
            {
                C.m[i][j] = (C.m[i][j] + A.m[i][k] * B.m[k][j]) % mod;
            }
        }
    }
    return C;
}
mat pow(mat A, ll n)
{
    mat B;
    B.m[0][0] = 8;
    B.m[1][0] = 10;
    B.m[2][0] = 2;
    B.m[3][0] = 9;
    B.m[4][0] = 3;
    B.m[5][0] = 1;
    while (n)
    {
        if (n & 1)
            B = mul(A, B);
        A = mul(A, A);
        n >>= 1;
    }
    return B;
}
int main()
{
    ll n;
    while (cin >> n&&n!=0)
    {
        mat A;
        A.m[0][0] = A.m[0][1]= A.m[0][3]=1;
        A.m[1][1] = 2;A.m[1][2]=3;A.m[1][4]=A.m[1][5]=1;
        A.m[2][1] = 1;
        A.m[3][3]=1;A.m[3][4]=2;A.m[3][5]=1;
        A.m[4][4] = A.m[4][5]=1;
        A.m[5][5] = 1;
        if(n==1)
            cout<<2<<endl;
        else if(n==2)
            cout<<8<<endl;
        else
        {
            mat B = pow(A, n-2);
            printf("%lld\n", B.m[0][0]);
        }
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/-citywall123/p/9992188.html