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 <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;
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值