您的位置:首页 > 编程语言 > C语言/C++

bnu新生赛D 柯南的精灵(矩阵快速幂)

2014-12-27 18:28 411 查看
题目地址:http://www.bnuoj.com/v3/contest_show.php?cid=5727#problem/D

学了矩阵快速幂之后,终于用到一次了。。没学之前天天遇到。。学了之后终于遇到一次了。。。特来纪念一下

分别设方程f(x)为发育期精灵,g(x)为更年期精灵,h(x)为天数。

然后

f(x-1)                      f(x)

g(x-1)   *   A    =     g(x)

h(x-1)                     h(x)

1                            1

关系矩阵为

0  y  p  0

x  z   0  0

0  0  1  1

0  0  0  1

然后利用矩阵快速幂即可。

代码如下:

#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
#include <queue>
#include <map>
#include <set>
#include <algorithm>

using namespace std;
#define LL long long
const int mod=1e9+7;
struct matrix
{
LL ma[5][5];
}init, res;
matrix Mult(matrix x, matrix y)
{
matrix tmp;
int i, j, k;
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
tmp.ma[i][j]=0;
for(k=0;k<4;k++)
{
tmp.ma[i][j]=tmp.ma[i][j]+x.ma[i][k]*y.ma[k][j];
}
}
}
return tmp;
}
matrix Pow(matrix x, LL k)
{
matrix tmp;
int i, j;
for(i=0;i<4;i++) for(j=0;j<4;j++) tmp.ma[i][j]=(i==j);
while(k)
{
if(k&1) tmp=Mult(tmp,x);
x=Mult(x,x);
k>>=1;
}
return tmp;
}
int main()
{
LL t, x, y, z, p, i, j, n, a[6];
LL ans1, ans2;
scanf("%lld",&t);
while(t--){
scanf("%lld%lld%lld%lld%lld",&x,&y,&z,&p,&n);
a[0]=a[1]=a[2]=0;a[3]=1;
memset(init.ma,0,sizeof(init.ma));
init.ma[0][1]=y;init.ma[0][2]=p;
init.ma[1][0]=x;init.ma[1][1]=z;
init.ma[2][2]=init.ma[2][3]=init.ma[3][3]=1;
res=Pow(init,n);
ans1=1*res.ma[0][3];
ans2=1*res.ma[1][3];
printf(">>%lld\n",ans1+ans2);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息