PAT甲题题解-1105. Spiral Matrix (25)-(模拟顺时针矩阵)
题意:给定N,以及N个数。找出满足m*n=N且m>=n且m-n最小的m、n值,建立大小为m*n矩阵,将N个数从大到下顺时针填入矩阵中。
#include <iostream> #include <cstdio> #include <algorithm> #include <string.h> #include <cmath> #define LEFT 1 #define RIGHT 2 #define UP 3 #define DOWN 4 using namespace std; const int maxn=10000+5; int a[maxn]; int n,m; int N; int main() { int **matrix; int tmp; scanf("%d",&N); tmp=(int)sqrt(N*1.0f+0.5); while(N%tmp!=0){ tmp++; } m=max(tmp,N/tmp); n=min(tmp,N/tmp); matrix=new int*[m]; for(int i=0;i<m;i++) matrix[i]=new int[n]; for(int i=0;i<N;i++) scanf("%d",&a[i]); sort(a,a+N); int p; int leftBound=0,rightBound=n-1,upBound=0,downBound=m-1; int x=0,y=0; int cnt=N; if(n>1) p=RIGHT; else p=DOWN; while(cnt){ matrix[y][x]=a[cnt-1]; if(p==RIGHT){ x++; if(x==rightBound){ upBound++; p=DOWN; } } else if(p==DOWN){ y++; if(y==downBound){ rightBound--; p=LEFT; } } else if(p==LEFT){ x--; if(x==leftBound){ downBound--; p=UP; } } else{ y--; if(y==upBound){ leftBound++; p=RIGHT; } } cnt--; } for(int i=0;i<m;i++){ for(int j=0;j<n-1;j++){ printf("%d ",matrix[i][j]); } printf("%d",matrix[i][n-1]); if(i<m-1) printf("\n"); } return 0; }