PAT 1050.螺旋矩阵(25)

#include <stdio.h>  
#include <iostream>  
#include <vector>  
#include <algorithm>  
#include<string>
#include<string.h>
#include<cmath>
using namespace std;

bool cmd(int a, int b)
{
	return a > b;
}

int a[100000000], num[10000][10000];

int main()
{
	int n;
	cin >> n;
	for (int i = 0; i < n; i++)
	{
		cin >> a[i];
	}
	sort(a, a + n, cmd);
	int minm = n, minn = 1;
	for (int i = n; i >= 1; i--)
	{
		if (n%i == 0)
		{
			if (i >= n / i)
			{
				if (i - n / i < minm - minn)
				{
					minm = i;
					minn = n / i;
				}
			}
		}
	}
	int rightz = 0, righty = minn, z = 0, downs = 1, downx = minm, leftz = 0, lefty = minn - 2, upx = minm - 2, ups = 1;
	int right = 0, left = minm - 1, up = 0, down = minn - 1;
	while (z != n)
	{
		for (int i = rightz; i < righty; i++)
		{
			if (z == n) break;
			num[right][i] = a[z++];
		}
		right++; rightz++; righty--;
		for (int i = downs; i < downx; i++)
		{
			if (z == n) break;
			num[i][down] = a[z++];
		}
		down--; downs++; downx--;
		for (int i = lefty; i >= leftz; i--)
		{
			if (z == n) break;
			num[left][i] = a[z++];
		}
		left--; lefty--; leftz++;
		for (int i = upx; i >= ups; i--)
		{
			if (z == n) break;
			num[i][up] = a[z++];
		}
		up++; upx--; ups++;
	}
	for (int i = 0; i < minm; i++)
	{
		for (int j = 0; j < minn; j++)
		{
			cout << num[i][j];
			if (j != minn - 1) cout << " ";
		}
		if (i != minm - 1) cout << endl;
	}
}


posted @ 2016-06-11 13:28  Archger  阅读(42)  评论(0编辑  收藏  举报