poj 3233 Matrix Power Series 构造矩阵求等比矩阵和

来源:互联网 发布:sl会员商城源码 编辑:程序博客网 时间:2024/06/05 05:56

Given a n × n matrix A and a positive integer k, find the sum S = A + A2 + A3 + … + Ak.

Input

The input contains exactly one test case. The first line of input contains three positive integers n (n ≤ 30), k (k ≤ 109) and m (m < 104). Then follow n lines each containing n nonnegative integers below 32,768, giving A’s elements in row-major order.

Output

Output the elements of S modulo m in the same way as A is given.

Sample Input
2 2 40 11 1
Sample Output
1 2

2 3

题意:已知一个n*n的矩阵A,和一个正整数k,求S A A2 A3 + … + Ak

思路:对于等比矩阵求和,我们就可以简单的构造一个矩阵

A A

0 E

然后对这个矩阵求快速幂会发现 该矩阵的二次方结果为

A A+A^2

0 E

要求S只需对构造的矩阵求n次方即可

#include<iostream>#include<cstdio>#include<cmath>#include<cstring>using namespace std;typedef struct {int s[100][100];int r,c;}Matrix;Matrix cot, w;int n,m,k;void creat(){    cin>>n>>k>>m;//构造矩阵     memset(cot.s,0,sizeof(cot.s));     for(int i=1;i<=n;i++)      for(int j=1;j<=n;j++)         {   scanf("%d",&cot.s[i][j]);   cot.s[i][j+n]=cot.s[i][j];    }  for(int i=1;i<=n;i++)   {          cot.s[i+n][i]=0;   }   for(int i=n+1;i<=2*n;i++)    for(int j=n+1;j<=2*n;j++)    {  if(i==j)         cot.s[i][j]=1;       else         cot.s[i][j]=0;}cot.r=cot.c=2*n; /*for(int i=1;i<=2*n;i++)   {   for(int j=1;j<=2*n;j++)   printf("%d ",cot.s[i][j]);   printf("\n");   }*/}Matrix mul(Matrix A,Matrix B){            Matrix ans;  memset(ans.s,0,sizeof(ans.s));       int i,j,k;       for(i=1;i<=2*n;i++)          for(j=1;j<=2*n;j++)          if(A.s[i][j]!=0)  {            for(k=1;k<=2*n;k++)           ans.s[i][k]=(ans.s[i][k]+A.s[i][j]*B.s[j][k])%m;           }    return ans;}Matrix Matrixpow(){     int i,j;     for(i=1;i<=2*n;i++)      for(j=1;j<=2*n;j++)       {  if(i==j)           w.s[i][j]=1;          else           w.s[i][j]=0;   }   while(k)   {   if(k&1)       w=mul(w,cot);       cot=mul(cot,cot);       k/=2;   }   return w;}void print(){    int i,j;     for(i=1;i<=n;i++)      {   for(j=n+1;j<=2*n;j++)       printf("%d ",w.s[i][j]);       printf("\n");  }  return ;}int main(){   creat();    Matrixpow();    print();    return 0;}

1 0
原创粉丝点击