HDU multi-school competition 9th games HDU 4965 Fast Matrix Calculation [matrix calculation + mathematical knowledge]

Source: Internet
Author: User

Difficulty, indeed, is not difficult

The problem is that there is a matrix operation optimization.

The question is to give matrix A of N * k to matrix B of K * n (1 <= n <= 1000 & 1 = <k <= 6 ), multiply them into a C matrix and calculate C ^ (N * n)

Equivalent

Ababababababab... = (AB) ^ (N * n)

Worse

A (BA) ^ (N * N-1) B

Because the BA multiplied K * k matrix, K is relatively small.

 

 

#include <cstdio>#include <cstdlib>#include <cstring>#include <cmath>#include <algorithm>#include <iostream>using namespace std;int a[1111][1111];int b[1111][1111];int c[1111][1111];int tmp[1111][1111];int sum[1111][1111];void TIMES(int K,int N,int M,int aa[][1111],int bb[][1111],int cc[][1111]){memset(tmp,0,sizeof(tmp));for(int i=1;i<=K;i++){for(int j=1;j<=M;j++){for(int k=1;k<=N;k++){tmp[i][j]=(tmp[i][j]+aa[i][k]*bb[k][j]%6)%6;}}}for(int i=1;i<=K;i++)for(int j=1;j<=M;j++)cc[i][j]=tmp[i][j]%6;}void quick(int cc[][1111],int mi,int n){for(int i=1;i<=n;i++)for(int j=1;j<=n;j++)if(i==j) sum[i][j]=1;else sum[i][j]=0;while(mi){if(mi&1)TIMES(n,n,n,cc,sum,sum);TIMES(n,n,n,cc,cc,cc);mi>>=1;}}int main(){#ifndef ONLINE_JUDGEfreopen("G:/in.txt","r",stdin);//freopen("G:/myout.txt","w",stdout);#endifint N,K;while(~scanf("%d%d",&N,&K)){if(N==0 && K==0) return 0;for(int i=1;i<=N;i++){for(int j=1;j<=K;j++){scanf("%d",&a[i][j]);}}for(int i=1;i<=K;i++){for(int j=1;j<=N;j++){scanf("%d",&b[i][j]);}}TIMES(K,N,K,b,a,c);quick(c,N*N-1,K);TIMES(N,K,K,a,sum,sum);TIMES(N,K,N,sum,b,sum);int ans=0;for(int i=1;i<=N;i++)for(int j=1;j<=N;j++)ans+=sum[i][j];cout<<ans<<endl;}}


 

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.