#include<bits/stdc++.h>
using namespace std;
#define N 8
int i,j;
int A[N][N],B[N][N],C[N][N];
void input(int n,int x[][N]){
for(i=0;i<n;i++)
for(j=0;j<n;j++){
cin>>x[i][j];
}
}
void output(int n,int x[][N]){
for(i=0;i<n;i++){
for(j=0;j<n;j++){
cout<<x[i][j]<<' ';
}
cout<<endl;
}
}
void Matrix_M(int n,int A[][N],int B[][N],int C[][N]){
for(i=0;i<n;i++)
for(j=0;j<n;j++){
C[i][j]=0;
for(int k=0;k<n;k++)
C[i][j]+=A[i][k]*B[k][j];
}
}
void Matrix_A(int n,int A[][N],int B[][N],int C[][N]){
for(i=0;i<n;i++)
for(j=0;j<n;j++){
C[i][j]=A[i][j]+B[i][j];
}
}
void Matrix_S(int n,int A[][N],int B[][N],int C[][N]){
for(i=0;i<n;i++)
for(j=0;j<n;j++){
C[i][j]=A[i][j]-B[i][j];
}
}
void Strassen(int n,int A[][N],int B[][N],int C[][N]){
int A11[N][N],A12[N][N],A21[N][N],A22[N][N];
int B11[N][N],B12[N][N],B21[N][N],B22[N][N];
int C11[N][N],C12[N][N],C21[N][N],C22[N][N];
int M1[N][N],M2[N][N],M3[N][N],M4[N][N],M5[N][N],M6[N][N],M7[N][N];
int T1[N][N],T2[N][N];
if(n==2){
Matrix_M(2,A,B,C);
return;
}
for(i=0;i<n/2;i++){
for(j=0;j<n/2;j++){
A11[i][j]=A[i][j];
A12[i][j]=A[i][j+n/2];
A21[i][j]=A[i+n/2][j];
A22[i][j]=A[i+n/2][j+n/2];
B11[i][j]=B[i][j];
B12[i][j]=B[i][j+n/2];
B21[i][j]=B[i+n/2][j];
B22[i][j]=B[i+n/2][j+n/2];
}
}
//M1=A11(B12-B22)
Matrix_S(n/2,B12,B22,T1);
Strassen(n/2,A11,T1,M1);
//M2=(A11+A12)B22
Matrix_A(n/2,A11,A12,T1);
Strassen(n/2,T1,B22,M2);
//M3=(A21+A22)B11
Matrix_A(n/2,A21,A22,T1);
Strassen(n/2,T1,B11,M3);
//M4=A22(B21-B11)
Matrix_S(n/2,B21,B11,T1);
Strassen(n/2,A22,T1,M4);
//M5=(A11+A22)(B11+B22)
Matrix_A(n/2,A11,A22,T1);
Matrix_A(n/2,B11,B22,T2);
Strassen(n/2,T1,T2,M5);
//M6=(A12-A22)(B21+B22)
Matrix_S(n/2,A12,A22,T1);
Matrix_A(n/2,B21,B22,T2);
Strassen(n/2,T1,T2,M6);
//M7=(A11-A21)(B11+B12)
Matrix_S(n/2,A11,A21,T1);
Matrix_A(n/2,B11,B12,T2);
Strassen(n/2,T1,T2,M7);
//C11=M5+M4-M2+M6
Matrix_A(n/2,M5,M4,T1);
Matrix_S(n/2,T1,M2,T2);
Matrix_A(n/2,T2,M6,C11);
//C12=M1+M2
Matrix_A(n/2,M1,M2,C12);
//C21=M3+M4
Matrix_A(n/2,M3,M4,C21);
//C22=M5+M1-M3-M7
Matrix_A(n/2,M5,M1,T1);
Matrix_S(n/2,T1,M3,T2);
Matrix_S(n/2,T2,M7,C22);
for(i=0;i<n/2;i++){
for(j=0;j<n/2;j++){
C[i][j]=C11[i][j];
C[i+n/2][j]=C21[i][j];
C[i][j+n/2]=C12[i][j];
C[i+n/2][j+n/2]=C22[i][j];
}
}
}
int main(){
int i,j,n;
cout<<"输入矩阵阶数:"<<endl;
cin>>n;
cout<<"输入第一个矩阵:"<<endl;
input(n,A);
cout<<"输入第二个矩阵:"<<endl;
input(n,B);
Strassen(n,A,B,C);
cout<<"结果为:"<<endl;
output(n,C);
return 0;
}