Fast power-related matrix

Fast Power matrix may be O (n) linear recursive optimization to O (log n), is a very good optimization

Did a lot of questions, feel better, I learned a lot.

However, doing P2151 [SDOI2009] HH go for a walk  when the people are autistic up. Autistic after a morning + noon, afternoon finally want to understand.

After AC, write a blog about the matter recorded rapid matrix powers.

  1. Handwritten matrix structure, package various functions.
     1 struct Mar{
     2     int a[maxm][maxm],n;
     3     Mar (int _n=0) {n=_n;memset(a,0,sizeof a);}//不传参数默认为0
     4     Mar operator ~ () {for(int i=0;i<n;i++) a[i][i]=1;}//单位矩阵
     5     Mar operator * (const Mar &b) const {
     6         Mar c(n);
     7         for(int i=0;i<n;i++) for(int j=0;j<n;j++) for(int k=0;k<n;k++)
     8             c.a[i][j]=(c.a[i][j]+a[i][k]%mod*b.a[k][j]%mod)%mod;
     9         return c;
    10     }
    11     Mar operator ^ (int b){//快速幂
    12         Mar c(n),x=*this;~c;//  "*this" 有意思
    13         while(b){
    14             if(b&1) c=c*x;
    15             x=x*x;
    16             b>>=1;
    17         }
    18         return c;
    19     }
    20 };
  2. Mar ans (15) indicates a length and width of the opening n matrix; Mar ans () denotes a length and width for the opening 0 of the matrix.
  3. Matrix multiplication is not commutative, to distinguish between left and right multiplication multiply;
  4. P2151 [SDOI2009] HH to walk  a little bit different, the relationship between the points is replaced Unicom Unicom side relationship, without the side edge unidirectional stored twice. I finally found a moment of multiplication principle:       Figure represents A * B = C

      It looks like the feeling of three views. Color line represents the length is equal, the blue line can be multiplied conditions.

      C in the i-th row, j-th column is equal to the value of the i-th row out of A, B of the j-th column out, put together sequentially multiplied (that is, the blue line and the like).

      Gone. .

Guess you like

Origin www.cnblogs.com/sdfzjdx/p/11258983.html