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 ncolumns, 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 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 93Sample Output:
98 95 93 42 37 81 53 20 76 58 60 76
题意:将N个数从大到小按蛇形的方式放入m行n列的矩阵,并且m*n=N,m>n,m-n最小
解题思路:先从小到大排序,然后按蛇形的方向(右下左上)填入矩阵
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <queue>
#include <vector>
#include <set>
#include <stack>
#include <map>
#include <climits>
#include <functional>
using namespace std;
#define LL long long
const int INF = 0x3f3f3f3f;
int a[10005],ans[1000][1000];
int n, r, c;
int dir[4][2] = {{-1,0},{0,1},{1,0},{ 0,-1 }};
int main()
{
while (~scanf("%d", &n))
{
int c = sqrt(n);
while (n%c != 0) c--;
r = n / c;
for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
sort(a + 1, a + 1 + n,greater<int>());
memset(ans, 0, sizeof ans);
int x = 1, y = 1,p=0;
for (int i = 1; i <= n; i++)
{
ans[x][y] = a[i];
if (i == n) break;
while (1)
{
int xx = x + dir[p][0];
int yy = y + dir[p][1];
if (ans[xx][yy] || xx<1 || xx>r || yy<1 || yy>c) { p++; p %= 4; continue; }
x = xx, y = yy; break;
}
}
for (int i = 1; i <= r; i++)
{
printf("%d", ans[i][1]);
for (int j = 2; j <= c; j++)
printf(" %d", ans[i][j]);
printf("\n");
}
}
return 0;
}