1. 程式人生 > >1105 Spiral Matrix (25 分)

1105 Spiral Matrix (25 分)

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; m≥n; and m−n 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 10​4​​. 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

蛇形排序    記錄下行起點 行終點 列起點 列終點

程式碼

#include<bits/stdc++.h>
using namespace std;
int digit[10005]; 
int maze[10001][10001];
bool cmp(int a,int b){
	return a > b;
}
int main()
{
	int k;
	scanf("%d",&k);
	int s = (int)sqrt(k);	
	int m, n;
	for(int i = s; i >= 1; i --)
	{
		if(k % i == 0)
		{
			m = k / i;
			n = i;
			break;
		}	
	}
	//說明此刻 m 是它的行數  n 是它的列數
	for(int i = 1; i <= k; i++)
		scanf("%d", &digit[i]);
	sort(digit + 1,digit + 1 + k,cmp);
	int now = 0;
	int bm = 1, bn = 1, em = m, en = n; 
	while(now < k)
	{
		for(int i = bn; i <= en; i++)
			maze[bm][i] = digit[++now];
		bm += 1;
		if(now >= k) break; 
		for(int i = bm; i <= em; i++)
			maze[i][en] = digit[++now];
		en -= 1;
		if(now >= k) break;
		for(int i = en; i >= bn; i--)
			maze[em][i] = digit[++now];
		em -= 1;
		if(now >= k) break;
		for(int i = em; i >= bm; i--)
			maze[i][bn] = digit[++now];
		bn += 1;
		if(now >= k) break;
	}
	for(int i = 1; i <= m; i ++){
		for(int j = 1; j <= n; j ++)
			printf("%d%c",maze[i][j]," \n"[j == n]);
	}
	return 0;
}