ZOJ Summer 2018 #include <list>

 For a sequence X. Xn+1 = ( a * Xn + c ) % p. Now given a, c, X0, n, p, you need to calculate Xn.

Input

The first line contains an integer T, indicating that there are T test cases (T <= 20); 
For each case: 
The only line of the input contains five integers a , c , X0 , n , p. ( a,c,p <= 1e9 , X0,n <= 1e18 )

Output

For each test case, output the integer Xn.

Sample Input

4
4 3 1 1 7
4 3 7 0 3
4 3 7 1 3
2018 7 15 8 31

Sample Output

0
7
1
10

矩阵快速幂

由题意构造

| a 1 |

| 0 1 |

然后矩阵快速幂一下即可

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<pair<ll,ll>,pair<ll,ll> > pll;
int T;
ll a,c,x0,n,p;
pll operator *(const pll &a,const pll &b)
{
    return make_pair( make_pair((a.first.first*b.first.first%p+a.first.second*b.second.first%p)%p,
                                (a.first.first*b.first.second%p+a.first.second*b.second.second%p)%p),
                     make_pair((a.second.first*b.first.first%p+a.second.second*b.second.first%p)%p,
                               (a.second.first*b.first.second%p+a.second.second*b.second.second%p)%p
                               ) );
}
ll F(ll y)
{
    pll ans=make_pair(make_pair(a,1),make_pair(0,1)),
         x=make_pair(make_pair(1,0),make_pair(0,1));
    while(y)
    {
        if(y&1) x=x*ans;
        ans=ans*ans;
        y>>=1;
    }
    return x0%p*x.first.first%p+x.first.second*c%p;
}

int main()
{
    cin>>T;
    while(T--)
    {
        cin>>a>>c>>x0>>n>>p;
        if(n==0) cout<<x0<<endl;
        else  cout<<F(n)%p<<endl;
    }
    return 0;
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值