您的位置:首页 > 其它

coj 1597

2016-05-15 01:17 281 查看


Description

薛XX的低IQ是个令人头疼的问题,他的队友深受其害。幸运的是,薛XX非常有钱,所以他买了一些可以提高他的后代的IQ的药。这种药有三个属性,A,B和P。当薛XX使用这种药的时候,他的基因会发生变化,所以他的儿子的IQ也会跟着变化。假设薛XX的父亲的IQ为X,薛XX自己的IQ为Y,那么薛XX的儿子的IQ为(A*X+B*Y) mod P。薛XX的孙子的IQ依次类推。

现在给定X和Y,还有药的属性A、B和P,现在他想知道他的N代子孙的IQ(儿子是第一代,孙子是第二代)。


Input

第一行包含一个整数T(T<=100),表示数据组数

每组数据只有一行,包含六个整数X,Y,A,B,P,N(1 ≤ X, Y ≤ 300,1 ≤ A, B ≤ 30, 1≤ P ≤ 300 , 1 ≤ N < 1000000000),含义如题目所述


Output

对于每组数据,输出答案


Sample Input

4
180 80 1 1 190 1
189 83 2 2 190 1
189 83 1 1 190 2
172 73 23 19 273 9999


Sample Output

70
164
165
233


一道矩阵快速幂的模板题,主要用来学习矩阵的快速幂

思路:构造两个矩阵

我们可以发现 A*B会得到第一代 A*(A*B )会得到第二代,又矩阵乘法满足结合律,所以第N代的矩阵可以是 A的N次幂乘以B得到,

这里就要用到矩阵的快速幂,思想类似于整数的快速幂

代码:

#include <iostream>
#include <cstring>
#include <stdio.h>
using namespace std;
typedef long long LL;
LL mod;
struct mat
{
int m,n;  //m*n的矩阵
LL s[3][3];
mat(int a,int b)
{
m=a,n=b;
memset(s,0,sizeof(s));
}
mat(int a,int b,LL w[][3])
{
m=a,n=b;
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
s[i][j]=w[i][j];
}
};
mat mat_mul(mat a,mat b)
{
mat c(a.m,b.n);
for(int i=0;i<a.m;i++)
{
for(int j=0;j<b.n;j++)
{
for(int k=0;k<a.n;k++)
{
c.s[i][j]+=a.s[i][k]*b.s[k][j];
c.s[i][j]%=mod;
}

}
}

return c;
}
mat blank(int m,int n)
{
mat a(m,n);
for(int i=0;i<m;i++)
a.s[i][i]=1;
return a;
}
mat mat_pow(mat a,LL b)
{

mat ret = blank(a.m,a.n);
while(b)
{
if(b&1)
ret=mat_mul(ret,a);
a = mat_mul(a,a);
b>>=1;
}
return ret;
}
int main()
{
//freopen("in.txt","r",stdin);
int t;
scanf("%d",&t);
while(t--)
{
int x,y,a,b,p,n;
scanf("%d%d%d%d%d%d",&x,&y,&a,&b,&p,&n);
mod=p;
LL w[][3]={{0,1},{a,b}};
LL z[][3]={{x},{y}};
mat aa(2,2,w);
mat bb(2,1,z);
aa=mat_pow(aa,n);
bb=mat_mul(aa,bb);
printf("%lld\n",bb.s[1][0]);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: