GYM 101061 G.Repeat it(dp+矩阵快速幂)

202 篇文章 1 订阅
52 篇文章 0 订阅

Description
给出一个数n,要把它重复m次,问最终得到的数字
Input
第一行一整数T表示用例组数,每组用例输入两个整数m和n表示重复次数和要重复的数字(1<=m<=1e9,0<=n<=1e9)
Output
输出n重复m次后的数字,结果模1e9+7
Sample Input
3
4 31
8 1
123 123
Sample Output
31313131
11111111
388853804
Solution
以dp[i]表示重复i次之后的值,那么有dp[i]=dp[i-1]*10^x+n,其中x是n的位数,用矩阵快速幂加速一下该转移即可,转移矩阵如下:
这里写图片描述
Code

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<ctime>
using namespace std;
typedef long long ll;
#define INF 0x3f3f3f3f
#define maxn 3
const ll mod=1e9+7ll; 
struct Mat
{
    ll mat[maxn][maxn];//矩阵 
    int row,col;//矩阵行列数 
};
Mat mod_mul(Mat a,Mat b,int p)//矩阵乘法 
{
    Mat ans;
    ans.row=a.row;
    ans.col=b.col;
    memset(ans.mat,0,sizeof(ans.mat));
    for(int i=0;i<ans.row;i++)      
        for(int k=0;k<a.col;k++)
            if(a.mat[i][k])
                for(int j=0;j<ans.col;j++)
                {
                    ans.mat[i][j]+=a.mat[i][k]*b.mat[k][j]%p;
                    ans.mat[i][j]%=p;
                }
    return ans;
}
Mat mod_pow(Mat a,int k,int p)//矩阵快速幂 
{
    Mat ans;
    ans.row=a.row;
    ans.col=a.col;
    for(int i=0;i<a.row;i++)
        for(int j=0;j<a.col;j++)
            ans.mat[i][j]=(i==j);
    while(k)
    {
        if(k&1)ans=mod_mul(ans,a,p);
        a=mod_mul(a,a,p);
        k>>=1;
    }
    return ans;
}
int T;
ll n,m;
int main()
{
    scanf("%d",&T);
    while(T--)
    {
        scanf("%I64d%I64d",&m,&n);
        ll temp=1,nn=n;
        while(nn)
        {
            temp*=10ll;
            nn/=10;
        }
        Mat A;
        A.row=A.col=2;
        A.mat[0][0]=temp%mod,A.mat[0][1]=n,A.mat[1][0]=0,A.mat[1][1]=1;
        A=mod_pow(A,m,mod);
        printf("%I64d\n",A.mat[0][1]);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值