您的位置:首页 > 其它

B1050. 螺旋矩阵(25)

2017-03-27 18:24 218 查看
本题要求将给定的N个正整数按非递增的顺序,填入“螺旋矩阵”。所谓“螺旋矩阵”,是指从左上角第1个格子开始,按顺时针螺旋方向填充。要求矩阵的规模为m行n列,满足条件:m*n等于N;m>=n;且m-n取所有可能值中的最小值。

输入格式:

输入在第1行中给出一个正整数N,第2行给出N个待填充的正整数。所有数字不超过104,相邻数字以空格分隔。

输出格式:

输出螺旋矩阵。每行n个数字,共m行。相邻数字以1个空格分隔,行末不得有多余空格。

输入样例:

12

37 76 20 98 76 42 53 95 60 81 58 93

输出样例:

98 95 93

42 37 81

53 20 76

58 60 76

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;

int N;
int pos = 0;
int ans[10000][10000] = { 0 };

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

int main()
{
vector<int> input;
int temp;
int row, col;
int flag = 0;
int  you = 0;//本来想着上下左右的,结果只用一个“右”就搞定

cin >> N;
for (int i = 0; i < N; ++i)
{
cin >> temp;
input.push_back(temp);
}
sort(input.begin(), input.end(),cmp);
//计算行列
for (int i = sqrt(N); i >=1; --i)
{
if (N%i == 0)
{
col = i;
row = N / i;
break;
}
}
//相应位置放入数据
while (pos < N)
{
for (int i = you; i < col - you&&flag==0; ++i)
{
ans[you][i] = input[pos];
++pos;
if (pos==N)
{
flag = 1;
break;
}
}
++you;
for (int i = you; i < row - you&&flag == 0; ++i)
{
ans[i][col - you] = input[pos];
++pos;
if (pos == N)
{
flag = 1;
break;
}
}
for (int i = col - you; i >= you-1 && flag == 0; --i)
{

ans[row-you][i] = input[pos];
++pos;
if (pos == N)
{
flag = 1;
break;
}
}

for (int i = row - you - 1 ; i >= you&& flag == 0; --i)
{
ans[i][you - 1] = input[pos];
++pos;
if (pos == N)
{
flag = 1;
break;
}
}
}
//输出
for (int i = 0; i < row; ++i)
{
for (int j = 0; j < col; ++j)
{
if (j == 0)
cout << ans[i][j];
else
cout << ' ' << ans[i][j];
}
cout << endl;
}

system("pause");
return 0;
}


为了方便理解,说下数据填入的模式:

1 1 1 1 1 1 1

4 5 5 5 5 5 2

4 8 9 9 9 6 2

4 8 a a a 6 2

4 7 7 7 7 7 2

3 3 3 3 3 3 3

就像上下夹层,把中间夹住
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: