CodeForces 678D Iterated Linear Function
简单矩阵快速幂。
#include<cstdio> #include<cstring> #include<cmath> #include<algorithm> #include<vector> #include<queue> #include<map> #include<stack> using namespace std; long long mod=1e9+7; long long n,A,B,x; struct Matrix { long long A[5][5]; int R, C; Matrix operator*(Matrix b); }; Matrix X, Y, Z; Matrix Matrix::operator*(Matrix b) { Matrix c; memset(c.A,0,sizeof c.A); int i, j, k; for (i = 1; i <= R; i++) for (j = 1; j <= C; j++) for (k = 1; k <= C; k++) c.A[i][j] = (c.A[i][j] + (A[i][k] * b.A[k][j])%mod)%mod; c.R=R; c.C=b.C; return c; } void init() { memset(X.A,0,sizeof X.A); memset(Y.A,0,sizeof Y.A); memset(Z.A,0,sizeof Z.A); for(int i=1;i<=2;i++) Y.A[i][i]=1; Y.R = 2; Y.C = 2; X.A[1][1]=1; X.A[1][2]=B%mod; X.A[2][1]=0; X.A[2][2]=A%mod; X.R=2; X.C=2; Z.A[1][1]=1; Z.A[1][2]=x%mod; Z.R=1; Z.C=2; } void work() { while (n) { if (n % 2 == 1) Y = Y*X; n = n >> 1; X = X*X; } Z = Z*Y; printf("%lld\n", Z.A[1][2]); } int main() { scanf("%lld%lld%lld%lld",&A,&B,&n,&x); init(); work(); return 0; }