HDU - 4686 Arc of Dream 矩阵高速幂
HDU - 4686 Arc of Dream 矩阵快速幂
题目大意:An Arc of Dream is a curve defined by following function:
Aod(n) = a0 * b0 + a1 * b1 + a2 * b2 … a(n-1) * b(n-1)
where
a 0 = A0
a i = a i-1*AX+AY
b 0 = B0
b i = b i-1*BX+BY
What is the value of AoD(N) modulo 1,000,000,007?
解题思路:这一题的矩阵构造还是挺麻烦的
由递推公式的an*bn = (an-1*Ax+Ay)*(bn-1*Bx+By) => an-1*bn-1*Ax*Bx+an-1*Ax*By+bn-1*Ay*Bx+Ay*By
坑点:注意long long 可能会溢出,乘的时候注意
#include<cstdio>
typedef long long ll;
const int N = 5;
const ll mod = 1e9 + 7;
ll n, A0, Ax, Ay, B0, Bx, By;
struct Matrix{
ll mat[N][N];
}A, B, tmp;
void init() {
for(int i = 0; i < N; i++)
for(int j = 0; j < N; j++) {
A.mat[i][j] = B.mat[i][j] = 0;
if(i == j)
B.mat[i][j] = 1;
}
A.mat[0][0] = A.mat[4][4] = 1;
A.mat[1][0] = A.mat[1][1] = (Ax * Bx) % mod;
A.mat[2][0] = A.mat[2][1] = (Ax * By) % mod;
A.mat[3][0] = A.mat[3][1] = (Ay * Bx) % mod;
A.mat[4][0] = A.mat[4][1] = (Ay * By) % mod;
A.mat[2][2] = Ax;
A.mat[4][2] = Ay;
A.mat[3][3] = Bx;
A.mat[4][3] = By;
}
Matrix matMul(Matrix x, Matrix y) {
for(int i = 0; i < N; i++)
for(int j = 0; j < N; j++) {
tmp.mat[i][j] = 0;
for(int k = 0; k < N; k++)
tmp.mat[i][j] = (tmp.mat[i][j] + (x.mat[i][k] * y.mat[k][j]) % mod) % mod;
}
return tmp;
}
void solve() {
while(n) {
if(n & 1)
B = matMul(B,A);
A = matMul(A,A);
n >>= 1;
}
}
int main() {
while(scanf("%I64d", &n) != EOF) {
scanf("%I64d%I64d%I64d", &A0, &Ax, &Ay);
scanf("%I64d%I64d%I64d", &B0, &Bx, &By);
if(n == 0) {
printf("0\n");
continue;
}
if(n == 1) {
printf("%I64d\n", (A0 * B0) % mod);
continue;
}
n--;
init();
solve();
ll ans = 0;
ans += (((A0 * B0) % mod) * B.mat[0][0] % mod);
ans += (((A0 * B0) % mod) * B.mat[1][0] % mod);
ans += (A0 * B.mat[2][0]) % mod;
ans += (B0 * B.mat[3][0]) % mod;
ans += (B.mat[4][0]) % mod;
printf("%I64d\n", ans % mod);
}
return 0;
}