HDU 5015 233 Matrix(矩阵快速幂模板)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/pqdong/article/details/79974117

Problem Description

In our daily life we often use 233 to express our feelings. Actually, we may say 2333, 23333, or 233333 … in the same meaning. And here is the question: Suppose we have a matrix called 233 matrix. In the first line, it would be 233, 2333, 23333… (it means a0,1 = 233,a0,2 = 2333,a0,3 = 23333…) Besides, in 233 matrix, we got ai,j = ai-1,j +ai,j-1( i,j ≠ 0). Now you have known a1,0,a2,0,…,an,0, could you tell me an,m in the 233 matrix?

Input

There are multiple test cases. Please process till EOF.

For each case, the first line contains two postive integers n,m(n ≤ 10,m ≤ 109). The second line contains n integers, a1,0,a2,0,…,an,0(0 ≤ ai,0 < 231).

Ouput

For each case, output an,m mod 10000007.

Sample Input

1 1
1
2 2
0 0
3 7
23 47 16

Sample Output

234
2799
72937

#include<iostream>
#include<cstring>
#include<cstdio>
#include<cstdlib>
#include<string>
#include<memory.h>
#include<algorithm>
using namespace std;
typedef long long LL;//一般结果都是很大的
const int N=12;//推导出来的矩阵T的大小
const int M=10000007;
LL tem[N][N];//临时数组
LL a[N][N];//矩阵T,推导出来的
LL res[N][N];//结果矩阵
LL b[N];//初始(原始的)矩阵
LL sum;
void mult(LL res[][N],LL a[][N]) {//矩阵相乘,脑袋短路竟然卡了形参传递问题
    LL tem[N][N];
    memset(tem,0,sizeof(tem));
    for(int i=0; i<N; i++) {
        for(int j=0; j<N; j++) {
            for(int k=0; k<N; k++) {
                tem[i][j]+=(res[i][k]*a[k][j])%M;
            }
        }
    }
    for(int i=0; i<N; i++) {
        for(int j=0; j<N; j++) {
            res[i][j]=tem[i][j];
        }
    }
    return;
}
void quick_mod(LL a[][N],LL n) {
    memset(res,0,sizeof(res));
    for(int i=0; i<N; i++) {
        res[i][i]=1;
    }
    while(n) {//矩阵快速幂
        if(n&1) {
            mult(res,a);
        }
        mult(a,a);
        for(int i=0;i<N;i++){
            for(int j=0;j<N;j++){
                cout<<a[i][j]<<" ";
            }
            cout<<endl;
        }
        cout<<endl;
        n>>=1;
    }
    return;
}
int main() {
    int n,m;
    while(scanf("%d%d",&n,&m)!=EOF) {
        memset(b,0,sizeof(b));
        //推导出的矩阵T
        memset(a,0,sizeof(a));
        for(int i=0; i<=10; i++) {
            a[i][0]=10;
            a[i][N-1]=1;
        }
        a[N-1][N-1]=1;
        for(int i=1; i<=10; i++) {
            for(int j=1; j<=i; j++) {
                a[i][j]=1;
            }
        }
        //初始(原始矩阵,通常是一维矩阵)
        b[0]=23;
        b[N-1]=3;
        sum=0;
        for(int i=1; i<=n; i++) {
            scanf("%lld",&b[i]);
        }
        quick_mod(a,m);//矩阵快速幂
        for(int i=0; i<N; i++) {
            sum+=(res[n][i]*b[i])%M;
        }
        printf("%lld\n",sum%M);
    }
    return 0;
}

另外附上快速幂的模板,矩阵快速幂其实就是整数快速幂推广到二维的结果

int quick_pow(int a,int b){
    int base=a;
    int res=1;
    while(b){
        if(b&1)res*=base;
        base*=base;
        b>>=1;
    }
    return res;
}
阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页