Covering(矩阵快速幂)
Bob's school has a big playground, boys and girls always play games here after school.
To protect boys and girls from getting hurt when playing happily on the playground, rich boy Bob decided to cover the playground using his carpets.
Meanwhile, Bob is a mean boy, so he acquired that his carpets can not overlap one cell twice or more.
He has infinite carpets with sizes of 1×21×2 and 2×12×1, and the size of the playground is 4×n4×n.
Can you tell Bob the total number of schemes where the carpets can cover the playground completely without overlapping?
Input
There are no more than 5000 test cases.
Each test case only contains one positive integer n in a line.
1≤n≤10181≤n≤1018
Output
For each test cases, output the answer mod 1000000007 in a line.
Sample Input
1 2
Sample Output
1 5
递推公式为F[N]=F[N-1]+5F[n-2]+F[n-3]-F[n-4];
这个题有个坑点,就是在取模之后数值会变小,然后导致系数为-的给减的导致最后的值是-的
这种问题我们的解法是在最后的结果+MOD再取模
学到了
代码:
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<queue>
#include<stack>
#include<set>
#include<vector>
#include<map>
#include<cmath>
#define MOD 1000000007
const int maxn=1e5+5;
typedef long long ll;
using namespace std;
struct mat
{
ll a[5][5];
};
mat Mul(mat a,mat b)
{
mat ans;
memset(ans.a,0,sizeof(ans.a));
for(int t=1;t<=4;t++)
{
for(int j=1;j<=4;j++)
{
for(int k=1;k<=4;k++)
{
ans.a[t][j]=(ans.a[t][j]+a.a[t][k]*b.a[k][j])%MOD;
}
}
}
return ans;
}
mat ans;
ll quickpow(ll n)
{
mat res;
memset(res.a,0,sizeof(res.a));
res.a[1][1]=1;
res.a[1][2]=5;
res.a[1][3]=1;
res.a[1][4]=-1;
res.a[2][1]=1;
res.a[3][2]=1;
res.a[4][3]=1;
while(n)
{
if(n&1)
{
ans=Mul(res,ans);
}
res=Mul(res,res);
n>>=1;
}
return ans.a[1][1];
}
int main()
{
ll n;
while(cin>>n)
{
memset(ans.a,0,sizeof(ans.a));
ans.a[1][1]=36;
ans.a[2][1]=11;
ans.a[3][1]=5;
ans.a[4][1]=1;
if(n==1)
{
printf("1\n");
}
else if(n==2)
{
printf("5\n");
}
else if(n==3)
{
printf("11\n");
}
else if(n==4)
{
printf("36\n");
}
else
{
ll s=quickpow(n-4)+MOD;
printf("%lld\n",(s)%MOD);
}
}
return 0;
}
-------------------------------------------
个性签名:独学而无友,则孤陋而寡闻。做一个灵魂有趣的人!
如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!
万水千山总是情,打赏一分行不行,所以如果你心情还比较高兴,也是可以扫码打赏博主,哈哈哈(っ•̀ω•́)っ✎⁾⁾!