POJ 3233 Matrix Power Series (Matrix optimization)

Source: Internet
Author: User
Tags bitset

POJ 3233 Matrix Power Series (Matrix optimization)

Ask S [k] = A + A ^ 2 +... + A ^ k

Using the rapid power of A matrix, we can quickly obtain the k power of A matrix, but this question is A sum. If we still follow the original method, we will calculate k times, which is unacceptable in complexity.

We can construct A matrix (A 0)

(E)

Now let S [k] = E + A ^ 2 +... + A ^ (k-1)

So (A ^ k) (A 0) (A ^ (k-1) (A 0) ^ k (E)

=

(S [k]) (E) (S [k-1]) (E) (0)

Then, we only need to calculate S [k + 1] = E + A +... + A ^ k

Then, just move the diagonal line element-1.

For details, see the code:

 

#include
 
  #include
  
   #include#include
   
    #include
    
     #include
     
      #include
      
       #include
       
        #include
        
         #include
         
          #include
          
           #include
           
            #include
            
             #include
             #include
              
               #define Max(a,b) ((a)>(b)?(a):(b))#define Min(a,b) ((a)<(b)?(a):(b))using namespace std;typedef long long ll;const double PI = acos(-1.0);const double eps = 1e-6;const int INF = 1000000000;const int mod = 10007;const int maxn = 100;int T,n,m,k;typedef vector
               
                 vec;typedef vector
                
                  mat;mat mul(mat &a, mat &b) { mat c(a.size(), vec(a[0].size())); for(int i = 0; i < a.size(); i++) { for(int k = 0; k < b.size(); k++) { for(int j = 0; j < b[0].size(); j++) { c[i][j] = (c[i][j] + a[i][k]*b[k][j]) % m; } } } return c;}mat pow(mat a, ll n) { mat b(a.size(), vec(a[0].size())); for(int i = 0; i < a.size(); i++) { b[i][i] = 1; } while(n > 0) { if(n & 1) b = mul(b, a); a = mul(a, a); n >>= 1; } return b;}int main() { scanf("%d%d%d",&n,&k,&m); mat a(2*n, vec(2*n)); for(int i=0;i 
                
               
              
            
           
          
         
        
       
      
     
    
   
  
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.