P3390 fast power solution of matrix

Title gate

Background of topic

Matrix fast power

Title Description

Given matrix A of n*n, find A^k

I / O format

Input format:

 

First line, n,k

Rows 2 to n+1, n numbers in each row, row i+1, and number j represent the elements in row i, column j of the matrix

 

Output format:

 

Output A^k

There are n rows in total, N in each row. The number of rows i and j represents the elements in row i and column J of the matrix, and each element module is 10 ^ 9 + 7

 

Example of input and output

Input example ා 1:

2 1
1 1
1 1

Output sample

1 1
1 1

N < = 100, K < = 10 ^ 12, | matrix element | < 1000 algorithm: matrix fast power

Explanation:

see Understanding matrix multiplication

Code:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<string>
#include<cstring> 
#define LL long long
#define MOD 1000000007
using namespace std;
LL a[109][109],ans[109][109],bak[109][109],K;
int n;
void Fast_Pow()
{
    while(K)
    {
        if(K%2) 
        {
            for(int i=1;i<=n;i++)
              for(int j=1;j<=n;j++)
                bak[i][j]=ans[i][j],ans[i][j]=0;
            for(int i=1;i<=n;i++) 
             for(int j=1;j<=n;j++)
              for(int k=1;k<=n;k++)
                ans[i][j]=(ans[i][j]+bak[i][k]*a[k][j]%MOD)%MOD;
        }
        for(int i=1;i<=n;i++) 
         for(int j=1;j<=n;j++)
          bak[i][j]=a[i][j],a[i][j]=0;
        for(int i=1;i<=n;i++)
         for(int j=1;j<=n;j++)
          for(int k=1;k<=n;k++)
           a[i][j]=(a[i][j]+bak[i][k]*bak[k][j]%MOD)%MOD;

        K/=2;
    }
}
int main()
{
    scanf("%d%lld",&n,&K);
    for(int i=1;i<=n;i++) 
      for(int j=1;j<=n;j++) 
          scanf("%lld",&a[i][j]);

    for(int i=1;i<=n;i++) 
      for(int j=1;j<=n;j++)
        ans[i][j]=a[i][j];


    K--;Fast_Pow();

    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=n;j++) printf("%lld ",ans[i][j]);
        puts("");
    }
    return 0;
} 

 

Posted by shivangp on Sat, 07 Dec 2019 07:53:59 -0800