hdu-5015(矩阵快速幂)

来源:互联网 发布:windows 多进程 编辑:程序博客网 时间:2024/05/22 15:56
233 Matrix
Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 65536/65536 K
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).
 
Output
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

题意:给出矩阵的第0行(233,2333,23333,...)和第0列a1,a2,...an(n<=10,m<=10^9),给出式子: A[i][j] = A[i-1][j] + A[i][j-1],要求A[n][m]。


如上图:红色部分为绿色部分之和,而顶上的绿色部分很好求,左边的绿色部分(最多10个)其实就是:A[1][m-1],A[2][m-1]..A[n][m-1],即对每个1<=i<=n, A[i][m]都可由A[1][m-1],A[2][m-1]..A[n][m-1],于是建立12*12的矩阵:

将中间矩阵求m-1次幂,与右边[A[0][1],A[1][1]..A[n][1],3]^T相乘,结果就可以得出了。

矩阵的幂可用快速幂算法。

#include<stdio.h>#include<string.h>#define mod 10000007#define ll __int64int n,m;struct matrix{ll x[12][12];}a;/*10,1,0,0,0,0,0,0,0,0,0,0, 0,1,0,0,0,0,0,0,0,0,0,0,10,1,1,0,0,0,0,0,0,0,0,0,10,1,1,1,0,0,0,0,0,0,0,0,10,1,1,1,1,0,0,0,0,0,0,0,10,1,1,1,1,1,0,0,0,0,0,0,10,1,1,1,1,1,1,0,0,0,0,0,10,1,1,1,1,1,1,1,0,0,0,0,10,1,1,1,1,1,1,1,1,0,0,0,10,1,1,1,1,1,1,1,1,1,0,0,10,1,1,1,1,1,1,1,1,1,1,0,10,1,1,1,1,1,1,1,1,1,1,1*/matrix operator * (matrix &s,matrix &z){matrix c;for(int i=0;i<n+2;i++)for(int j=0;j<n+2;j++){c.x[i][j]=0;for(int k=0;k<n+2;k++)c.x[i][j]=(c.x[i][j]+(s.x[i][k]*z.x[k][j])%mod)%mod;}return c;}matrix pow(matrix s,int z)//快速幂{matrix c;memset(c.x,0,sizeof(c.x));for(int i=0;i<n+2;i++)c.x[i][i]=1;while(z)      {          if(z&1) c=c*s;          s=s*s;          z>>=1;      }  return c;}int main(){ll b[12];b[0]=23;b[1]=3;for(int i=0;i<12;i++)for(int j=0;j<12;j++){if(j==0){if(i!=1) a.x[i][j]=10;else a.x[i][j]=0;}else{if(j<=i) a.x[i][j]=1;else a.x[i][j]=0;}}a.x[0][1]=1;while(scanf("%d%d",&n,&m)!=EOF){for(int i=2;i<n+2;i++)scanf("%I64d",&b[i]);matrix c;ll z[12];memset(z,0,sizeof(z));c=pow(a,m);for(int j=0;j<n+2;j++)for(int k=0;k<n+2;k++)z[j]=(z[j]+(c.x[j][k]*b[k])%mod)%mod;printf("%I64d\n",z[n+1]);}return 0;}


0 0
原创粉丝点击