P3390 [TEMPLATE] rapid matrix power, p3390 Matrix

Source: Internet
Author: User

P3390 [TEMPLATE] rapid matrix power, p3390 Matrix
Background

Rapid matrix power

Description

Given n * n matrix A, evaluate A ^ k

Input/Output Format Input Format:

The first line, n, k

The number of n rows from 2nd to n + 1. The number of j rows in I + 1 indicates the elements in column j of row I in the matrix.

Output Format:

Output A ^ k

N rows in total, n numbers in each row, and j numbers in row I represent the elements in column j of row I. Each element is 10 ^ 9 + 7

Input and Output sample Input example #1:
2 11 11 1
Output sample #1:
1 11 1
Description

N <= 100, k <= 10 ^ 12, | matrix element | <= 1000 algorithm: rapid matrix power

 

Bare question !.

Note that the tmp value is accumulated when the matrix is multiplied.

 1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<cmath> 5 #define LL long long  6 using namespace std; 7 const int mod = 1e9+7; 8 LL n,k; 9 LL a[101][101];10 LL tmp[101][101];11 LL ans[101][101];12 void mul(LL a[][101],LL b[][101])13 {14     memset(tmp,0,sizeof(tmp));15     for(int i=1;i<=n;i++)16         for(int j=1;j<=n;j++)17             for(int k=1;k<=n;k++)18                 tmp[i][j]+=a[i][k]*b[k][j]%mod;19             20     for(int i=1;i<=n;i++)21         for(int j=1;j<=n;j++)22             a[i][j]=tmp[i][j]%mod; 23 }24 void fastpow(LL a[][101],LL k)25 {26     27     for(int i=1;i<=n;i++)ans[i][i]=1;28     while(k)29     {30         if(k%2)mul(ans,a);31         mul(a,a);32         k/=2;33     }34     for(int i=1;i<=n;i++)35     {36         for(int j=1;j<=n;j++)37             cout<<ans[i][j]%mod<<" ";38         printf("\n");39     }40         41 }42 int main()43 {44     cin>>n>>k;45     for(int i=1;i<=n;i++)46         for(int j=1;j<=n;j++)47             cin>>a[i][j];48     fastpow(a,k);49     return 0;50 }

 

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.