1. 程式人生 > >[NOI2012]隨機數生成器

[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;
}