[NOI2012]随机数生成器

嘟嘟嘟


这题就是一道矩阵加速dp的水题,dp式都给你了,所以矩阵这方面就不说了。
之所以发这篇博客,是因为两数相乘可能会爆long long,所以得用快速乘。
现学了一下,感觉和快速幂特别像。
对于两个数(a, b),按位枚举(b),如果(b)的第(i)位为(1),答案就加上(a * 2 ^ i)
发一下代码。

#include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<vector>
#include<stack>
#include<queue>
using namespace std;
#define enter puts("") 
#define space putchar(' ')
#define Mem(a, x) memset(a, x, sizeof(a))
#define rg register
typedef long long ll;
typedef double db;
const int INF = 0x3f3f3f3f;
const db eps = 1e-8;
//const int maxn = ;
inline ll read()
{
	ll ans = 0;
	char ch = getchar(), last = ' ';
	while(!isdigit(ch)) {last = ch; ch = getchar();}
	while(isdigit(ch)) {ans = (ans << 1) + (ans << 3) + ch - '0'; ch = getchar();}
	if(last == '-') ans = -ans;
	return ans;
}
inline void write(ll x)
{
	if(x < 0) x = -x, putchar('-');
	if(x >= 10) write(x / 10);
	putchar(x % 10 + '0');
}

ll mod, a, c, x0, n, g;
ll mul(ll a, ll b)	//神奇的快速乘 
{
    ll ret = 0;
    for(; b; b >>= 1, a = (a << 1) % mod) 
        if(b & 1) ret = (ret + a) % mod;
    return ret;
}
const int N = 2;
struct Mat
{
	ll a[N][N];
  	Mat operator * (const Mat& oth)const
	{
		Mat ret; Mem(ret.a, 0);
	    for(int i = 0; i < N; ++i)
	    	for(int j = 0; j < N; ++j)
	    		for(int k = 0; k < N; ++k)
	      			ret.a[i][j] += mul(a[i][k], oth.a[k][j]), ret.a[i][j] %= mod;
		return ret;
	}
}F;
void init()
{
	Mem(F.a, 0);
	F.a[0][0] = a; F.a[0][1] = F.a[1][1] = 1;
}
Mat quickpow(Mat A, ll b)
{
	Mat ret; Mem(ret.a, 0);
	for(int i = 0; i < N; ++i) ret.a[i][i] = 1;
  	for(; b; b >>= 1, A = A * A)
    	if(b & 1) ret = ret * A;
  	return ret;
}

int main()
{
	mod = read(), a = read(), c = read(), x0 = read(), n = read(), g = read();
	a %= mod; c %= mod; x0 %= mod;
	init();
	Mat A = quickpow(F, n);
	write((mul(A.a[0][0], x0) + mul(A.a[0][1], c)) % mod % g), enter;
	return 0;
}
原文地址:https://www.cnblogs.com/mrclr/p/10146584.html