#include<iostream>
#include<conio.h>
#include<iomanip>
using namespace std;
void nhapmang(int a[][100],int& n);
void xuatmanghaichieu(int a[][100], int n);
void haithanhmot(int b[100],int a[][100],int n);
void xeptang(int b[],int n);
void matranxoanoc(int a[][100],int n);
int a[100][100],b [100],n,k;
void main()
{
nhapmang(a,n);
matranxoanoc(a,n);
}
void nhapmang(int a[][100],int& n)
{
cout<<"Cho biet ma tran cap may: ";
cin>>n;
cout<<"Nhap cac phan tu cua ma tran: \n";
for(int i=0;i<n;++i)
for(int j=0;j<n;++j)
{
cout<<"a["<<i+1<<"]["<<j+1<<"]= ";
cin>>a[i][j];
}
}
void xuatmanghaichieu(int a[][100], int n)
{
cout<<"Cac phan tu cua ma tran la: \n";
for(int i=0;i<n;++i)
{
for(int j=0;j<n;++j)
cout<<setw(3)<<a[i][j];
cout<<endl;
}
}
void haithanhmot(int b[100],int a[][100],int n)
{
int k=0;
for(int i=0;i<n;++i)
for(int j=0;j<n;++j)
b[k++]=a[i][j];
xeptang(b,n*n);
}
void xeptang(int b[],int n)
{
int t;
for(int i=1;i<n;++i)
for(int j=n-1;j>=i;--j)
if(b[j]<b[j-1])
{
t=b[j];
b[j]=b[j-1];
b[j-1]=t;
}
}
void matranxoanoc(int a[][100],int n)
{
int d=0,dem=1,b[100],c[100][100],l=n-1;
int i=0,j=0;
haithanhmot(b,a,n);
int m=(n%2)?n*n-1:n*n;
while(d<m)
{
switch(dem)
{
case 1:
{
for(int t=0;t<l;++t)
c[i][j+t]=b[d++];
j=j+l;dem++;
}break;
case 2:
{
for(int t=0;t<l;++t)
c[i+t][j]=b[d++];
i=i+l;dem++;
}break;
case 3:
{
for(int t=0;t<l;++t)
c[i][j-t]=b[d++];
j=j-l;dem++;
}break;
case 4:
{
for(int t=0;t<l;++t)
c[i-t][j]=b[d++];
dem=1;i=i-l+1;j=j+1;l=l-2;
}break;
}
}
if(n%2) c[n/2][n/2]=b[n*n-1];
xuatmanghaichieu(c,n);
}