1105. Spiral Matrix (25)

#include <iostream>
#include <algorithm>
#include <algorithm>

using namespace std;

int num[10010], arr[110][110];

int cmp(int a, int b)
{
	return a > b;
}

int main()
{
	int d;
	scanf("%d", &d);

	int i;
	for(i = 1; i <= d; i++)
	{
		scanf("%d", &num[i]);
	}

	int begin = sqrt(d * 1.0);
	while(begin * begin < d)
	{
		begin++;
	}

	int m, n;
	for(i = begin; i <= d; i++)
	{
		if(d % i == 0)
		{
			m = i;
			n = d / i;
			break;
		}
	}

	sort(num + 1, num + d + 1, cmp);

	int x = 1, y = 0, count = 0;
	while(count < d)
	{
		while(count < d && y + 1 <= n && arr[x][y + 1] == 0)
		{
			arr[x][++y] = num[++count];
		}
		while(count < d && x + 1 <= m && arr[x + 1][y] == 0)
		{
			arr[++x][y] = num[++count];
		}
		while(count < d && y - 1 >= 1 && arr[x][y - 1] == 0)
		{
			arr[x][--y] = num[++count];
		}
		while(count < d && x - 1 >= 1 && arr[x - 1][y] == 0)
		{
			arr[--x][y] = num[++count];
		}
	}
	
	int j;
	for(i = 1; i <= m; i++)
	{
		for(j = 1; j <= n; j++)
		{
			if(j > 1)
			{
				printf(" ");
			}

			printf("%d", arr[i][j]);
		}

		printf("\n");
	}

	system("pause");
	return 0;
}

 

posted on 2025-11-25 09:10  王景迁  阅读(0)  评论(0)    收藏  举报

导航