HDU 6172 Array Challenge (矩阵快速幂+打表)

Problem Description
There’s an array that is generated by following rule.
h0=2,h1=3,h2=6,hn=4hn1+17hn212hn316
And let us define two arrays bnandan as below.
bn=3hn+1hn+9hn+1hn1+9h2n+27hnhn118hn+1126hn81hn1+192(n>0)
an=bn+4n
Now, you have to print (an) , n>1.
Your answer could be very large so print the answer modular 1000000007.
 

Input
The first line of input contains T (1 <= T <= 1000) , the number of test cases.
Each test case contains one integer n (1 < n <= 1015) in one line.
 

Output
For each test case print &#8970;√(a_n )&#8971; modular 1000000007.
 
Sample Input
3
4
7
9
Sample Output
1255
324725
13185773


 2017年多校第十场的题,当时做的时候看到数据范围和对1e9+7取余很容易想到是矩阵快速幂。


 暴力写了前几项,发现分别是31,197,1255,7997,50959


发现:


7*197-4*31=1255


7*1255-4*197=7997


7*7997-4*1255=50959


于是递推式很容易看出来了了 √an=7*√an-1-4*√an-2


写一个2*2的矩阵即可


如果猜的和h(n)公式一样,那么需要写一个3*3的矩阵



#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include<queue>
#include<map>
#include<algorithm>
#include<iostream>
#define ll long long
#define ull unsigned long long
const int N=1e9+7;
const int M=1e6+5;
using namespace std;

struct node
{
    ll jz[2][2];
} d,e;

node cf(node a,node b) //矩阵乘法
{
    node c;
    int i,j,k;
    memset(c.jz,0,sizeof(c.jz));
    for(i=0; i<2; i++)
    {
        for(j=0; j<2; j++)
        {
            for(k=0; k<2; k++)
            {
                c.jz[i][j]+=(a.jz[i][k]*b.jz[k][j]);
                c.jz[i][j]%=N;
            }
        }
    }
    return c;
}

ll ksm(ll x)  //矩阵快速幂
{
    if(x==2) return 31;
    if(x==3) return 197;
    memset(d.jz,0,sizeof(d.jz));
    for(int i=0; i<2; i++)
    {
        d.jz[i][i]=1;
    }
    e.jz[0][0]=7,e.jz[0][1]=-4;
    e.jz[1][0]=1,e.jz[1][1]=0,
    x-=3;
    while(x)
    {
        if(x&1) d=cf(d,e);
        e=cf(e,e);
        x>>=1;
    }
    ll sum=197*d.jz[0][0]%N+31*d.jz[0][1]%N;
    sum=(sum%N+N)%N;
    return sum;
}

int main()
{
    int T;
    scanf("%d",&T);
    ll n;
    while(T--)
    {
        scanf("%I64d",&n);
        printf("%I64d\n",ksm(n));
    }
    return 0;
}






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值