PAT甲级1105
原创
©著作权归作者所有:来自51CTO博客作者wx630c98f24f6b8的原创作品,请联系作者获取转载授权,否则将追究法律责任
1105. Spiral Matrix (25)
时间限制
150 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue
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 93
Sample Output:
98 95 93
42 37 81
53 20 76
58 60 76
#include<iostream>
#include<vector>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<iomanip>
using namespace std;
int cmp(int a, int b)
{
return a > b;
}
/*public class Helix {
static int N = 0;
public static int Helix(int x, int y) {
if ((x==1) && (y==1)) return 1;
if ((x-y>=1)&&(x+y<=N)) return (1 + Helix(x+1,y));
if ((x-y>=1)&&(x+y>N)) return (1 + Helix(x, y+1));
if ((x-y<1)&&(x+y<=N+1)) return (1 + Helix(x, y-1));
if ((x-y<1)&&(x+y)>N+1) return (1 + Helix(x-1,y));
else return 0;}
public static void main(String[] args) {
N = //输入int值;
for (int i= 1; i <= N; i++){
for (int j= 1; j <= N; j++)
System.out.print(Helix(i,j) + "\t");
System.out.println(""); }
}}这个就是先把矩阵每个位置二元组转换成一维时对应的数值求出来,我转别人的,不是自己想的,实质就是迷宫求解问题
*/
int main()
{
int N;
cin >> N;
int t;
int N1 = N;
vector<int> v;
while (N--)
{
cin >> t;
v.push_back(t);
}
sort(v.begin(), v.end(), cmp);//非递增
int i;
for (i = sqrt(N1); i <= N1; i++)
{
if (N1%i == 0)
break;
}//m和n肯定一个小于等于N平方根另一个大于等于N平方根
int m = max(i,N1/i), n = N1 / m;
int**a = new int*[m];
for (int i = 0; i < m; i++)
{
a[i] = new int[n];
}
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
a[i][j] = 0;
}
}//必须初始化为0
i = 0;
int x = 0, y = 0;
while (i < N1)
{
while (y < n&&!a[x][y])
a[x][y++] = v[i++];
y--;
x++;
while (x < m && !a[x][y])
a[x++][y] = v[i++];
x--;
y--;
while (y >= 0 && !a[x][y])
a[x][y--] = v[i++];
y++;
x--;
while (x >= 0 && !a[x][y])
a[x--][y] = v[i++];
x++;
y++;
}//螺旋放置的过程:先声明横坐标x和纵坐标y,然后类似走迷宫的方式,若前面能走(即判断下一个位置是否为0,不为0就不能进行赋值了)
//分为四个过程,右下左上,依次进行即可
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
cout << a[i][j];
if (j != n - 1)
cout << " ";
else
cout << endl;
}
}
return 0;
}