Codeforces 678 D. Iterated Linear Function(构造矩阵)

传送门
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

题目大意:

f(x)=Ax+B,g0(x)=x,gn(x)=f(gn1(x))gn(x)MOD(109+7)

解题思路:
首先将
gn(x)=f(gn1(x))=Agn1(x)+B

那么现在我们可以构造一个矩阵A使得:
(gn1(x),B)A=(gn(x),B)

那么矩阵A
[A101]

所以

(g0(x),B)An=(gn(x),B)

也就是说
gn(x)=g0(x)An(0,0)+BAn(1,0)

剩下的就是矩阵快速幂了和编码了,这个就参考一下我的代码就行了 。
My Code:

#include 
#include 
#include 
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; ifor(int j=0; j0;
            for(int k=0; kreturn 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<return 0;
}

你可能感兴趣的:(ACM_矩阵+高斯,ACM_Codeforces,ITAK的ACM之路)