地址:https://nanti.jisuanke.com/t/31721
矩阵快速幂
这道题是根据递推关系构造矩阵
取每2个观察递推关系
1,aa 2,ab 3,ac 4,ba 5,bb 6,bc 7,ca 8,cb 9,cc
添加第三位,1 –> 2,3。 2 –>4,5。 3 –> 7,8,9。 4 –> 1,3。5 –> 4,6。6–>7,9。7 –> 1,2,3。8 –> 5,6。9 –> 7,8。
则可得到 4,7 –> 1; 1,7–>2; 1,4,7 –> 3; 2,5 –> 4; 2,8 –> 5; 5,8 –> 6; 3,6,9 –> 7; 3,9 –> 8;
3,6 –> 9;
得到下一个是由哪前几个得到的
建立递推矩阵
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
typedef long long LL;
const LL MAXN = 1e9 + 7;
typedef struct node{
LL arr[9][9];
}node;
node mul(node n,node m)
{
node x;
int i,j,k;
for(i = 0;i < 9;++i)
{
for(j = 0;j < 9;++j)
{
x.arr[i][j] = 0;
for(k = 0;k < 9;++k)
{
x.arr[i][j] = (x.arr[i][j] + (n.arr[i][k] % MAXN * m.arr[k][j] % MAXN) % MAXN) % MAXN;
}
}
}
return x;
}
node Pow_mod(node n,LL m)
{
node ans;
int i,j;
for(i = 0;i < 9;++i)
{
for(j = 0;j < 9;++j)
{
if(j == i)
ans.arr[i][j] = 1;
else{
ans.arr[i][j] = 0;
}
}
}
while(m)
{
if(m & 1)
ans = mul(ans,n);
n = mul(n,n);
m >>= 1;
}
return ans;
}
int main()
{
int t;
scanf("%d",&t);
node mat = {0,0,0,1,0,0,1,0,0,
1,0,0,0,0,0,1,0,0,
1,0,0,1,0,0,1,0,0,
0,1,0,0,1,0,0,0,0,
0,1,0,0,0,0,0,1,0,
0,0,0,0,1,0,0,1,0,
0,0,1,0,0,1,0,0,1,
0,0,1,0,0,0,0,0,1,
0,0,1,0,0,1,0,0,0
};
/*int i,j;
for(i = 0;i < 7;++i)
{
for(j = 0;j < 7;++j)
{
cout<<mat.arr[i][j]<<" ";
}
cout<<endl;
}*/
while(t--)
{
LL n;
scanf("%lld",&n);
if(n == 1){
printf("3\n");
}else if(n == 2){
printf("9\n");
}else{
node x = Pow_mod(mat,n - 2LL);
LL ans = 0;
for(int i = 0;i < 9;++i)
{
for(int j = 0;j < 9;++j)
{
ans = (ans + x.arr[i][j]) % MAXN;
}
}
printf("%lld\n",ans);
}
}
return 0;
}