HDU 4291:A Short problem_成都赛区网络赛—矩阵快速幂

Problem Description
  According to a research, VIM users tend to have shorter fingers, compared with Emacs users.
  Hence they prefer problems short, too. Here is a short one:
  Given n (1 <= n <= 10 18), You should solve for 
g(g(g(n))) mod 10 9 + 7

  where
g(n) = 3g(n - 1) + g(n - 2)

g(1) = 1

g(0) = 0

 

Input
  There are several test cases. For each test case there is an integer n in a single line.
  Please process until EOF (End Of File).
 

Output
  For each test case, please print a single line with a integer, the corresponding answer to this case.
 

Sample Input
  
  
0 1 2
 

Sample Output
  
  
0 1 42837
 

Source

//一道类似斐波拉契的题,自己构造矩阵乘法。不同的是本题有三重嵌套函数,值最后去模(10^9+7),那么里面两层不能直接模(10^9+7),因为n与n对(10^9+7)的模数对于g(n)的值不一定相同。 因为类似斐波拉契的数列都有一个循环节,那么可以利用模数10^9+7求出第二层的循环节,将它作为模数再求出第一层的循环节。 求循环节的方法只要在另外写程序暴力便可以了。比赛的时候一个细节错误导致求错了一个循环节,1个多小时才出了这题。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
#include<cstdlib>
#include<queue>
#include<stack>
#include<map>
#include<vector>
#include<algorithm>
#include<ctime>
using namespace std;
#define LL unsigned long long

LL n;
struct Mat
{
    LL a00,a01,a10,a11;
};
LL mul_mod(LL a,LL b,LL m)  
{
	LL ans=0;
	LL d=a%m;
	while(b)
	{
		if(b&1)ans=ans+d;
		if(ans>=m)ans-=m;
		d<<=1;
		if(d>=m)d-=m;
		b>>=1;
	}
	return ans%m;
}

Mat mutilMat(Mat a, Mat b,LL m)
{
    Mat c;
    c.a00=(mul_mod(a.a00,b.a00,m)+mul_mod(a.a01,b.a10,m))%m;
    c.a01=(mul_mod(a.a00,b.a01,m)+mul_mod(a.a01,b.a11,m))%m;
    c.a10=(mul_mod(a.a10,b.a00,m)+mul_mod(a.a11,b.a10,m))%m;
    c.a11=(mul_mod(a.a10,b.a01,m)+mul_mod(a.a11,b.a11,m))%m;
    return c;
}
Mat powerMat(LL n,LL m)
{
    if(n==0)
    {
        Mat m0;
        m0.a00=1,m0.a01=0,m0.a10=0,m0.a11=1;
        return m0;
    }
    else
    {
        Mat a, b;
        a=powerMat(n/2,m),b=mutilMat(a,a,m);
        if(n%2!=0)
        {
            Mat m1;
            m1.a00=3,m1.a01=1,m1.a10=1,m1.a11=0;
            b=mutilMat(b, m1,m);
        }
        return b;
    }
}

int main()
{
	LL t,i;
	LL m0=183120ll,m1=222222224ll,m2=1000000007ll;
	while(~scanf("%I64u",&n))
	{
        Mat r=powerMat(n,m0);
        n=r.a01%m0;
		r=powerMat(n,m1);
        n=r.a01%m1;
		r=powerMat(n,m2);
        printf("%I64u\n",r.a01%m2);
	}
    return 0;
}
 



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值