您的位置:首页 > 其它

FZU 2198 快来快来数一数(矩阵快速幂)

2015-10-06 20:42 507 查看
/*
a[i]=6*a[i-1]-a[i]+1;

矩阵快速幂+预处理

vc++可过。。。。
*/
# include <stdio.h>
# include <algorithm>
# include <string.h>
# include <math.h>
using namespace std;
struct node
{
__int64 m[3][3];
};
const __int64 mod=1000000007;
node f(node a,node b)
{
int i,j,k;
node c;
for(i=0; i<3; i++)
for(j=0; j<3; j++)
{
c.m[i][j]=0;
for(k=0; k<3; k++)
{
c.m[i][j]=(c.m[i][j]+((a.m[i][k]*b.m[k][j]))+mod)%mod;
//c.m[i][j]%=mod;
}
}
return c;
}
node quick(node origin,__int64 n)
{

node answ;
memset(answ.m,0,sizeof(answ));
for(int i=0; i<3; i++)
answ.m[i][i]=1;
while(n)
{
if(n%2==1)
{
answ=f(origin,answ);

}
origin=f(origin,origin);
n/=2;
}
return answ;
}

int main()
{

int t;
__int64 n;
node o,answ;
memset(o.m,0,sizeof(o.m));
o.m[0][0]=6;
o.m[0][1]=1;
o.m[1][0]=-1;
o.m[2][0]=1;
o.m[2][2]=1;

memset(answ.m,0,sizeof(answ.m));
answ.m[0][0]=7;
answ.m[0][1]=1;
answ.m[0][2]=1;

node hehe[80];
hehe[1]=o;
for(int i=2; i<70; i++)//预处理
{
hehe[i]=f(hehe[i-1],hehe[i-1]);
}
while(~scanf("%d",&t))
{
while(t--)
{
scanf("%I64d",&n);
if(n==1)
printf("6\n");
else if(n==2)
printf("41\n");
else
{
node B;
memset(B.m,0,sizeof(B.m));
n--;
for(int i=0; i<3; i++)
B.m[i][i]=1;
for (int i = 1; n; i++, n >>= 1)
{
if (n&1)
B=f(B, hehe[i]);
}
node t=f(answ,B);
printf("%I64d\n",(t.m[0][0]-1+mod)%mod);
}
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: