HDU 5015 233 Matrix(矩阵快速幂)

233 Matrix

Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 2540    Accepted Submission(s): 1487


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 a 0,1 = 233,a 0,2 = 2333,a 0,3 = 23333...) Besides, in 233 matrix, we got a i,j = a i-1,j +a i,j-1( i,j ≠ 0). Now you have known a 1,0,a 2,0,...,a n,0, could you tell me a n,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 ≤ 10 9). The second line contains n integers, a 1,0,a 2,0,...,a n,0(0 ≤ a i,0 < 2 31).
 

Output
For each case, output a n,m mod 10000007.
 

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

Sample Output
 
   
234 2799 72937
Hint
 

Source
2014 ACM/ICPC Asia Regional Xi'an Online

【思路】
所求的是矩阵的第n行、第m列的元素,而每一列都可以由前一列递推得来,所以在这里可以构造一个矩阵A,令A与矩阵列向量做矩阵乘法,从而来得到下一个列向量。我们用b来表示当前列的列向量,当前已知的也只有第0列了,为了保持和此后向量的一致性,我们令b[0]=23,b[1]...b[n]不变,b[n+1]=3,递推便可以通过左乘下面构造出来矩阵来进行。由矩阵乘法的性质,我们可以先通过矩阵快速幂取模来得到A的m次方取模,再求结果。

【代码】
#include
#include
using namespace std;

const int MAXN=14,MOD=1e7+7;

int n,m;
int b[MAXN];

struct matrix{
    long long a[MAXN][MAXN];

    matrix()
    {
        memset(a,0,sizeof(a));
    }

    matrix operator*(const matrix &another)
    {
        matrix ans;
        for(int i=0;i<=n+1;i++)
            for(int j=0;j<=n+1;j++){
                for(int k=0;k<=n+1;k++)
                    ans.a[i][j]+=a[i][k]*another.a[k][j];
                ans.a[i][j]%=MOD;
            }
        return ans;
    }
};

matrix qpow(matrix a,int b)
{
    matrix ans;
    for(int i=0;i<=n+1;i++)ans.a[i][i]=1;
    while(b!=0){
        if(b&1==1)
            ans=ans*a;
        a=a*a;
        b>>=1;
    }
    return ans;
}

int main()
{
    while(scanf("%d %d",&n,&m)==2){
        b[0]=23;b[n+1]=3;
        for(int i=1;i<=n;i++)scanf("%d",&b[i]);
        matrix mat;
        for(int i=0;i<=n;i++)
            mat.a[i][0]=10;
        for(int i=1;i<=n;i++){
            for(int j=1;j<=i;j++)
                mat.a[i][j]=1;
            mat.a[i][n+1]=1;
        }
        mat.a[0][n+1]=1;
        mat.a[n+1][n+1]=1;
        matrix mat1=qpow(mat,m);
        long long ans=0;
        for(int i=0;i<=n+1;i++)
            ans=(ans+mat1.a[n][i]*b[i])%MOD;
        printf("%lld\n",ans);
    }
    return 0;
}


你可能感兴趣的:(矩阵快速幂)