1105 Spiral Matrix (25分)

This time your job is to fill a sequence of N positive integers into a spiral matrix in non-increasing order. A spiral matrix is filled in from the first element at the upper-left corner, then move in a clockwise spiral. The matrix has m rows and n columns, where m and n satisfy the following: m×n must be equal to N; mn; and mn is the minimum of all the possible values.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N. Then the next line contains N positive integers to be filled into the spiral matrix. All the numbers are no more than 104. The numbers in a line are separated by spaces.

Output Specification:

For each test case, output the resulting matrix in m lines, each contains n numbers. There must be exactly 1 space between two adjacent numbers, and no extra space at the end of each line.

Sample Input:

12
37 76 20 98 76 42 53 95 60 81 58 93

Sample Output:

98 95 93
42 37 81
53 20 76
58 60 76

题目描述:将一组数用二维数组的形式输出(类似漩涡),m-行,n-列,要求m>=n。

解题思路:将题目给的数组从大到小排序,然后求出二维数组的行和列,再往里面填值就行了。可以用一个二维数组vis记录哪个空是填了值的,比较方便。(在ccf真题中有一道题与这题类似,难度在第二道题)


#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e4 + 5;
int v[maxn];
vector<vector<int> > G;
vector<vector<bool> > vis;
bool cmp(int a, int b){
	return a > b;
}
int main()
{
	int n, k, x, y;
	scanf("%d", &n);
	for(int i=0; i<n; i++) scanf("%d", &v[i]);
	sort(v, v+n, cmp);
	x = sqrt(n)+1;
	for(int i=x; i>=1; i--){
		if(n%i==0){
			x = i;
			break;
		}
	}
	y = min(x,n/x); x = max(x,n/x);
	if(y==1){
		for(int i=0; i<n; i++) printf("%d\n", v[i]);
		return 0;
	}
	G.resize(x+1); vis.resize(x+1);
	for(int i=1; i<=x; i++){
		G[i].resize(y+2);
		vis[i].resize(y+2);
		vis[i][0] = false; vis[i][y+1] = false;
		for(int j=1; j<=y; j++) vis[i][j] = true;
	}
	int i = 1, j = 1, c=0;
	while(vis[i][j]&&c<n){//圈 
		while(j<=y&&vis[i][j]){
			G[i][j] = v[c];
			vis[i][j] = false;
			c++; j++;
		}
		i++; j--;
		while(i<=x&&vis[i][j]){
			G[i][j] = v[c];
			vis[i][j] = false;
			c++; i++;
		}
		i--; j--;
		while(j>=1&&vis[i][j]){
			G[i][j] = v[c];
			vis[i][j] = false;
			c++; j--;
		}
		j++; i--;
		while(i>=1&&vis[i][j]){
			G[i][j] = v[c];
			vis[i][j] = false;
			c++; i--;
		}
		i++; j++;
	}
	for(i=1; i<=x; i++){
		for(j=1; j<=y; j++){
			if(j!=1) printf(" ");
			printf("%d", G[i][j]);
		}
		printf("\n");
	}
	return 0;
}