1. 程式人生 > >hdu 5015 (矩陣快速冪)

hdu 5015 (矩陣快速冪)

遞推公式:

 (圖源網路)

#include<iostream>
#include<string>
#include<cstdio>
#include<cstring>
#include<queue>
#include<map>
#include<cmath>
#include<stack>
#include<set>
#include<vector>
#include<algorithm>
#define ll long long
#define inf 1<<30
using namespace std;
int MAXN;
int mod;
struct Matrix
{
	ll mat[15][15];
	Matrix() {}
	Matrix operator*(Matrix const &b)const
	{
		Matrix res;
		memset(res.mat, 0, sizeof(res.mat));
		for (int i = 1 ;i <=MAXN; i++)
			for (int j = 1; j <= MAXN; j++)
				for (int k = 1; k <=MAXN; k++)
					res.mat[i][j] = (res.mat[i][j]+this->mat[i][k] * b.mat[k][j])%mod;
		return res;
	}
};
Matrix pow_mod(Matrix base, int n)
{
	Matrix res;
	memset(res.mat, 0, sizeof(res.mat));
	for (int i = 1; i <=MAXN; i++)
		res.mat[i][i] = 1;
	while (n > 0)
	{
		if (n & 1) res = res*base;
		base = base*base;
		n >>= 1;
	}
	return res;
}
int s[150];
int main()
{
    int n,k,m;
    Matrix base,a;
    while(~scanf("%d%d",&n,&m))
    {
        mod=10000007;
        s[1]=23;
        for(int i=2;i<=n+1;i++)
        {
            scanf("%d",&s[i]);
        }
        n+=2;
        s[n]=3;
        MAXN=n;
        memset(base.mat,0,sizeof(base.mat));
        for(int i=1;i<n;i++)
        {
            for(int j=1;j<=n;j++)
            {
                if(j==1) base.mat[i][j]=10;
                else if(j==n) base.mat[i][j]=1;
                else
                {
                    if(j<=i) base.mat[i][j]=1;
                }
            }
        }
        base.mat[n][n]=1;
        Matrix ans=pow_mod(base,m);
        ll sum=0;
        for(int i=1;i<=n;i++)
        {
            sum=(sum+(ans.mat[n-1][i]*s[i])%mod)%mod;
        }
        printf("%lld\n",sum);
    }
}