poj 3233 快速幂+矩阵性质_codestorm_新浪博客

本文介绍了使用快速幂算法解决矩阵快速幂问题的方法,通过构建特定矩阵B进行迭代计算,最终得到答案矩阵。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目要领:
1,矩阵的快速幂
2.由于相乘一次元素值就很大,且对m取模的话取模时机不影响所以每次都取
3.令 B= [
          [A A]
          [0 I]
        ]

则 B^k = [
           [A^k   A ... A^k]
           [0          I   ]
         ]
则矩阵B的k次方的有上角即为答案。



  1. #include   
  2. #include   
  3. using namespace std;  
  4. #define MAXV 70  
  5.   
  6. typedef struct{  
  7.     int r,c;            //c行r列  
  8.     int mat[MAXV][MAXV];  
  9. }Matrix;  
  10.   
  11. Matrix ans,cnt;  
  12. int n,k,m;  
  13.   
  14. void Input(){  
  15.     int i,j;  
  16.       
  17.     memset(cnt.mat,0,sizeof(cnt.mat));  
  18.     memset(ans.mat,0,sizeof(ans.mat));  
  19.     for(i=0;i
  20.         for(j=0;j
  21.             scanf("%d",&cnt.mat[i][j]);  
  22.     }  
  23.     for(i=0;i
  24.         cnt.mat[i+n][i+n]=cnt.mat[i][i+n]=1;  
  25.         ans.mat[i][i]=ans.mat[i+n][i+n]=1;  
  26.     }  
  27.   
  28.       
  29.     cnt.c=cnt.r=2*n;  
  30.     ans.c=ans.r=2*n;  
  31. }  
  32.   
  33. Matrix MatrixMul(Matrix x,Matrix y){    //矩阵乘法  
  34.     Matrix t;  
  35.     int i,j,v;  
  36.     memset(t.mat,0,sizeof(t.mat));  
  37.     t.c=x.c;  
  38.     t.r=y.r;  
  39.   
  40.     for(i=0;i
  41.         for(j=0;j
  42.             for(v=0;v
  43.                 t.mat[i][j]+=((x.mat[i][v]*y.mat[v][j])%m);  
  44.             t.mat[i][j]=t.mat[i][j]%m;  
  45.         }  
  46.     return t;  
  47. }  
  48.   
  49. void Binary(){  
  50.     //二分快速幂  
  51.     k++;  
  52.     while(k){  
  53.         if(k & 1) ans=MatrixMul(ans,cnt);  
  54.         cnt=MatrixMul(cnt,cnt);  
  55.         k=k>>1;  
  56.     }  
  57. }  
  58.   
  59. void Output(){  
  60.       
  61.     int i,j;  
  62.     for(i=0;i
  63.         for(j=0;j
  64.             if(i!=j)  
  65.                 printf("%d ",ans.mat[i][j+n]);  
  66.             else  
  67.                 printf("%d ",ans.mat[i][j+n]-1);  
  68.         printf("\n");  
  69.     }  
  70. }  
  71.   
  72. int main(){  
  73.     while(~scanf("%d%d%d",&n,&k,&m)){  
  74.         Input();  
  75.         Binary();  
  76.         Output();  
  77.     }  
  78.     return 0;  
  79. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值