码迷,mamicode.com
首页 > 其他好文 > 详细

BZOJ 2875: [Noi2012]随机数生成器( 矩阵快速幂 )

时间:2015-08-12 23:33:21      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:

技术分享

矩阵快速幂...+快速乘就OK了 

--------------------------------------------------------------------------------------

#include<bits/stdc++.h>
 
using namespace std;
 
typedef long long ll;
 
ll MOD, a, c, x, n, g;
 
ll MUL(ll a, ll b) {
ll ans = 0;
for(; b; b >>= 1) {
if(b & 1) ans += a;
if(ans >= MOD) ans -= MOD;
a <<= 1;
if(a >= MOD) a -= MOD;
}
return ans;
}
 
struct matrix {
ll x[2][2];
matrix() {
memset(x, 0, sizeof x);
}
inline void unit() {
x[0][0] = x[1][1] = 1;
x[0][1] = x[1][0] = 0;
}
matrix operator * (const matrix &o) {
matrix ans;
for(int i = 0; i < 2; i++)
   for(int j = 0; j < 2; j++)
       for(int k = 0; k < 2; k++)
           (ans.x[i][j] += MUL(x[i][k], o.x[k][j])) %= MOD;
return ans;
}
matrix operator = (const matrix &o) {
memcpy(x, o.x, sizeof x);
return *this;
}
matrix operator ^ (ll k) {
matrix ans, p = *this; ans.unit();
for(; k; k >>= 1) {
if(k & 1) ans = ans * p;
p = p * p;
}
return ans;
}
} Q;
 
int main() {
cin >> MOD >> a >> c >> x >> n >> g;
Q.x[0][0] = a; Q.x[0][1] = 0; Q.x[1][0] = c; Q.x[1][1] = 1;
matrix ans = Q ^ n;
cout << (MUL(x, ans.x[0][0]) + ans.x[1][0]) % MOD % g << "\n";
return 0;
}

--------------------------------------------------------------------------------------

2875: [Noi2012]随机数生成器

Time Limit: 10 Sec  Memory Limit: 512 MB
Submit: 1289  Solved: 731
[Submit][Status][Discuss]

Description

Input

包含6个用空格分割的m,a,c,X0,n和g,其中a,c,X0是非负整数,m,n,g是正整数。

Output

输出一个数,即Xn mod g

Sample Input


11 8 7 1 5 3


Sample Output

2

HINT

Source

 

BZOJ 2875: [Noi2012]随机数生成器( 矩阵快速幂 )

标签:

原文地址:http://www.cnblogs.com/JSZX11556/p/4725747.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!