hdu 3483 A Very Simple Problem 矩阵快速幂+二项式展开

http://acm.hdu.edu.cn/showproblem.php?pid=3483


求Sn=1^x * x^1 + 2^x * x^2 +...+ n^x * x^n;


要从n^x转到(n+1)^x需要用到二项式展开公式

    (n+1)^x= 

C(x,0)  *n^0

C(x,1)  *n^1

C(x,2) *n^2

 ...

C(x,x) *n^x

因此可以得到:

设f(n,x)=x^n*n^x

f(n+1,x+1)=

 x^(n+1)(n+1)^x= 

x*C(x,0)  *x^n*n^0

x*C(x,1)  *x^n*n^1

x*C(x,2) *x^n*n^2

 ...

x*C(x,x) *x^n*n^x

=

x*C(x,0)  *f(n,0)

x*C(x,1)  *f(n,1)

x*C(x,2) *f(n,2)

 ...

x*C(x,x) *f(n,x)

 


因此维护一个 ori矩阵 [  Sn  f(n,0)  f(n,1)    f(n,2)  ...    f(n,x)   ]

构造系数矩阵

相乘得到 【 S(n+1)   f(n+1,0)  f(n+1,1)    f(n+1,2)  ...    f(n+1,x)    】

矩阵快速幂即可

#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;

  long long  mod=1000000007;
  long long cc[55][55];  //内存限制为 C(n,k)中的n*k
void pre()
{
	int i,j;
	for (i=0;i<=50;i++)
	{
		cc[i][0]=1;  //c(i,0)=1;
	}
	for (i=1;i<=50;i++)
 	{
		for (j=1;j<=50;j++)
		cc[i][j]=(cc[i-1][j-1]+cc[i-1][j])%mod;
	}
}

const int N = 52;
struct Matrix
{
    long long mat[N][N];
} ;
Matrix unit_matrix ;
long long n ,x;
const int k=52;
Matrix mul(Matrix a, Matrix b) //矩阵相乘
{
    Matrix res;
    for(int i = 0; i < k; i++)
        for(int j = 0; j < k; j++)
        {
            res.mat[i][j] = 0;
            for(int t = 0; t < k; t++)
            {
                res.mat[i][j] += a.mat[i][t] * b.mat[t][j];
                res.mat[i][j] %= mod;
            }
        }

    return res;
}

Matrix pow_matrix(Matrix a, long long m)  //矩阵快速幂
{
    Matrix res = unit_matrix;
    while(m != 0)
    {
        if(m & 1)
            res = mul(res, a);
        a = mul(a, a);
        m >>= 1;
    }
    return res;
}

Matrix get(long long n,long long  x)
{

    Matrix ori;
    memset(  ori.mat ,0,sizeof ori.mat);
    ori.mat[0][0]=x;
    for (int i=1;i<x+2;i++)   ori.mat[0][i]=x%mod;
    Matrix c;
    memset(  c.mat ,0,sizeof c.mat);
    c.mat[0][0]=1%mod;
    for (int i=1;i<x+2;i++)
    c.mat[i][0]=x*cc[x][i-1]%mod;
    for( int i=1;i<x+2;i++)
    for (int j=1;j<i+1;j++)
        c.mat[j][i]=x*cc[i-1][j-1]%mod;

    Matrix ans = pow_matrix(c, n-1);
    ans = mul(ori,ans);
    return ans;
}
int main()
{

    int  i, j, t;
    //初始化单位矩阵            //类似快速幂的 ans=1; 如今是ans=单位矩阵
    memset(unit_matrix.mat,0,sizeof unit_matrix.mat);
    for(i = 0; i < k; i++)  unit_matrix.mat[i][i] = 1;

    while(scanf("%lld%lld%lld",&n,&x,&mod))
    {
        if (n<0&&x<0&&mod<0)return 0;
        pre();
        Matrix tmp=get(n,x);
        long long ans=tmp.mat[0][0] ;
        printf("%lld\n",(ans));
    }
    return 0;
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值