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
Sample Output
Source
2012 ACM/ICPC Asia Regional Chengdu Online
//一道类似斐波拉契的题,自己构造矩阵乘法。不同的是本题有三重嵌套函数,值最后去模(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;
}