本題要求計算線性同餘生成器的第 n 項:xₙ = (a·xₙ₋₁ + c) mod mod,並輸出 xₙ mod g。直接模擬需 O(n) 時間,對於大 n 會超時。利用矩陣快速冪可將複雜度降至 O(log n)。
構造狀態向量:
[ xₙ ] [ a 0 ] [ xₙ₋₁ ] [ c ] [ 1 ] = [ c 1 ] [ 1 ] [ 1 ] (模 mod 運算)
令轉移矩陣 A = [[a, 0], [c, 1]],則有:
[ xₙ ] [ a 0 ]ⁿ [ x₀ ] [ 1 ] = [ c 1 ] [ 1 ]
unsigned long long fast_mul(unsigned long long x, unsigned long long y, unsigned long long mod) {
unsigned long long res = 0;
while (y) {
if (y & 1) res = (res + x) % mod;
x = (x + x) % mod;
y >>= 1;
}
return res;
}
struct Matrix {
unsigned long long a[2][2];
Matrix operator*(const Matrix &other, unsigned long long mod) const {
Matrix res = {{0}};
for (int i = 0; i < 2; ++i)
for (int k = 0; k < 2; ++k)
for (int j = 0; j < 2; ++j)
res.a[i][j] = (res.a[i][j] + fast_mul(a[i][k], other.a[k][j], mod)) % mod;
return res;
}
};
Matrix fast_pow(Matrix base, unsigned long long exp, unsigned long long mod) {
Matrix res = {{{1,0},{0,1}}}; // 單位矩陣
while (exp) {
if (exp & 1) res = res * base * mod;
base = base * base * mod;
exp >>= 1;
}
return res;
}
此題展示了矩陣快速冂在線性遞推加速中的強大威力,結合快速乘處理大數取模,是競賽編程中的經典技巧組合。