1105 Spiral Matrix (Analog, 21 and 25 points)

1105 Spiral Matrix (25 points)

Ideas:

Perform the simulation filling in the lower right and upper left in turn.

21 points:

#include <bits/stdc++.h>
#define debug(x) cout<<#x<<":"<<x<<endl;
#define f(i,a,n) for(int i=a;i<n;++i)
#define ff(i,a,n) for(int i=a;i<=n;++i)
const int INF=0x3f3f3f3f;
using namespace std;
typedef long long ll;
//
const int N=1e5+5,M=1e4;//题目没给定范围,可以开大一些
int a[N],res[M][M];
int n;
int main(){
    
    
    cin>>n;
    f(i,0,n){
    
    
        cin>>a[i];
    }
    int row,col;//row>col
    for(int i=1;i*i<=n;i++){
    
    
        if(n%i==0)col=i;
    }
    row=n/col;
    sort(a,a+n,greater<int>());
    //debug(row)debug(col)
    int l=0,r=col,u=0,d=row;
    int num=0;
    int p;
    while(num<n){
    
    
        p=l;
        while(p<r)res[u][p++]=a[num++];
        p=u+1;//注意+1,否则出现覆盖现象
        while(p<d)res[p++][r-1]=a[num++];
        p=r-2;//注意-2
        while(p>=l)res[d-1][p--]=a[num++];
        p=d-2;
        while(p>u)res[p--][l]=a[num++];

        l++,r--,u++,d--;
    }
    f(i,0,row)
        f(j,0,col){
    
    
        if(j!=col-1)cout<<res[i][j]<<" ";
        else cout<<res[i][j]<<endl;
    }
    return 0;
}

25 points:

#include <bits/stdc++.h>
#define debug(x) cout<<#x<<":"<<x<<endl;
#define f(i,a,n) for(int i=a;i<n;++i)
#define ff(i,a,n) for(int i=a;i<=n;++i)
const int INF=0x3f3f3f3f;
using namespace std;
typedef long long ll;
//
const int N=1e5+5,M=1e4;//题目没给定范围,可以开大一些
int a[N],res[M][M];
int n;
int main(){
    
    
    cin>>n;
    f(i,0,n){
    
    
        cin>>a[i];
    }
    int row,col;//row>col
    for(int i=1;i*i<=n;i++){
    
    
        if(n%i==0)col=i;
    }
    row=n/col;
    sort(a,a+n,greater<int>());
    //debug(row)debug(col)
    int l=0,r=col,u=0,d=row;
    int num=0;
    int p;
    while(num<n){
    
    
        p=l;
        while(p<r && num<n)res[u][p++]=a[num++];
        p=u+1;//注意+1,否则出现覆盖现象
        while(p<d && num<n)res[p++][r-1]=a[num++];
        p=r-2;//注意-2
        while(p>=l && num<n)res[d-1][p--]=a[num++];
        p=d-2;
        while(p>u && num<n)res[p--][l]=a[num++];

        l++,r--,u++,d--;
    }
    f(i,0,row)
        f(j,0,col){
    
    
        if(j!=col-1)cout<<res[i][j]<<" ";
        else cout<<res[i][j]<<endl;
    }
    return 0;
}

analyze:

Since the rectangle is different, the angle of the final filling is also different, so the filling may end at different angles. If it does not end at this time, it may cause 0 elements to overwrite the previous value. Therefore, when there is no number, the filling should be ended in advance.

Guess you like

Origin blog.csdn.net/qq_45550375/article/details/123765759