1050 螺旋矩阵

tech2023-11-26  32

思路:求出n,m,用while不停更新位置

#pragma GCC optimize(2) #include <cstdio> #include <cstring> #include <algorithm> #include <set> #include<iostream> #include<vector> #include<queue> #include<map> #include<stack> #include<iomanip> #include<bits/stdc++.h> using namespace std; typedef long long ll; #define SIS std::ios::sync_with_stdio(false) #define space putchar(' ') #define enter putchar('\n') #define lson root<<1 #define rson root<<1|1 typedef pair<int,int> PII; const int mod=1000000007 ; const int N=2e6+10; const int M=1e3+10; const int inf=0x7f7f7f7f; const int maxx=2e5+7; const double eps=1e-6; ll gcd(ll a,ll b) { return b==0?a:gcd(b,a%b); } ll lcm(ll a,ll b) { return a*(b/gcd(a,b)); } template <class T> void read(T &x) { char c; bool op = 0; while(c = getchar(), c < '0' || c > '9') if(c == '-') op = 1; x = c - '0'; while(c = getchar(), c >= '0' && c <= '9') x = x * 10 + c - '0'; if(op) x = -x; } template <class T> void write(T x) { if(x < 0) x = -x, putchar('-'); if(x >= 10) write(x / 10); putchar('0' + x % 10); } ll qsm(int a,int b,int p) { ll res=1%p; while(b) { if(b&1) res=res*a%p; a=1ll*a*a%p; b>>=1; } return res; } int a[100005]; int ans[10005][1005]; int main() { int n; scanf("%d",&n); for(int i=1;i<=n;i++) scanf("%d",&a[i]); sort(a+1,a+1+n,greater<int>()); int m=sqrt(n); int x,y; for(int i=m;i>=0;i--){ if(n%i==0){ x=i;y=n/x; break; } } if(y>x)swap(x,y); int cnt=0; int l=1,h=0; while(cnt<n) { //cout<<x<<' '<<y<<endl; while(h<y&&!ans[l][h+1]) ans[l][++h]=a[++cnt]; while(l<x&&!ans[l+1][h]) ans[++l][h]=a[++cnt]; while(h>1&&!ans[l][h-1]) ans[l][--h]=a[++cnt]; while(l>1&&!ans[l-1][h]) ans[--l][h]=a[++cnt]; } for(int i=1;i<=x;i++) { for(int j=1;j<=y-1;j++) { printf("%d ",ans[i][j]); } printf("%d\n",ans[i][y]); } return 0; }
最新回复(0)