传送门
D. Iterated Linear Function
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
Consider a linear function f(x) = Ax + B. Let’s define g(0)(x) = x and g(n)(x) = f(g(n - 1)(x)) for n > 0. For the given integer values A, B,n and x find the value of g(n)(x) modulo 109 + 7.
Input
The only line contains four integers A, B, n and x (1 ≤ A, B, x ≤ 109, 1 ≤ n ≤ 1018) — the parameters from the problem statement.
Note that the given value n can be too large, so you should use 64-bit integer type to store it. In C++ you can use the long longinteger type and in Java you can use long integer type.
Output
Print the only integer s — the value g(n)(x) modulo 109 + 7.
Examples
input
3 4 1 1
output
7
input
3 4 2 1
output
25
input
3 4 3 1
output
79
题目大意:
解题思路:
首先将
那么现在我们可以构造一个矩阵A使得:
那么矩阵A
所以
也就是说
剩下的就是矩阵快速幂了和编码了,这个就参考一下我的代码就行了 。
My Code:
#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
const int MAXN = 2;
typedef long long LL;
typedef struct
{
LL mat[MAXN][MAXN];
} Matrix;
const LL MOD = 1e9+7;
///求得的矩阵
Matrix P;
///单位矩阵
Matrix I = {1, 0,
0, 1,
};
///矩阵乘法
Matrix Mul_Matrix(Matrix a, Matrix b)
{
Matrix c;
for(int i=0; i<MAXN; i++)
{
for(int j=0; j<MAXN; j++)
{
c.mat[i][j] = 0;
for(int k=0; k<MAXN; k++)
{
c.mat[i][j] += (a.mat[i][k] * b.mat[k][j]) % MOD;
c.mat[i][j] %= MOD;
}
}
}
return c;
}
///矩阵的快速幂
Matrix quick_Mod_Matrix(LL m)
{
Matrix ans = I, b = P;
while(m)
{
if(m & 1)
ans = Mul_Matrix(ans, b);
m>>=1;
b = Mul_Matrix(b, b);
}
return ans;
}
int main()
{
LL A, B, n, x;
while(cin>>A>>B>>n>>x)
{
P.mat[0][0] = A, P.mat[0][1] = 0;
P.mat[1][0] = 1, P.mat[1][1] = 1;
Matrix tmp = quick_Mod_Matrix(n);
LL ans = x*tmp.mat[0][0] + B*tmp.mat[1][0];
ans = (ans%MOD+MOD)%MOD;
cout<<ans<<endl;
}
return 0;
}