CF-C.Palindromic Matrix(回文方阵)

tech2022-08-05  133

Input 4 1 8 8 1 2 2 2 2 2 2 2 2 1 8 8 1 Output YES 1 2 2 1 8 2 2 8 8 2 2 8 1 2 2 1 Input 3 1 1 1 1 1 3 3 3 3 Output YES 1 3 1 3 1 3 1 3 1 Input 4 1 2 1 9 8 4 3 8 8 3 4 8 9 2 1 1 Output NO Input 1 10 Output YES 10

-横竖都要回文数

#include <bits/stdc++.h> using namespace std; typedef long long ll; int n, k, flag; map<int, int> mp; queue<int> q1; queue<int> q2; queue<int> q4; int arr[25][25], cur, a, b; void run(){ if(flag==1){ cout << "NO\n"; return ; } cout << "YES\n"; for(int i = 1; i <= n; i ++){ for(int j = 1; j <= n; j ++){ if(j!=1)cout << " "; cout << arr[i][j]; } cout << endl; } } void r0(){ for(int i = 1; i <= n/2; i ++){ for(int j = 1; j <= n/2; j ++){ if(q4.empty()){flag=1;return;}; cur = q4.front(), q4.pop(); arr[i][j] = cur; arr[n-i+1][j] = cur; arr[i][n-j+1] = cur; arr[n-i+1][n-j+1] = cur;//四个镜像位置 } } } void r1(){ arr[n/2+1][n/2+1] = q1.front(), q1.pop();//正中间 int step = -1; if(q2.size()%2==1){flag=1;return;} for(int i = n; i >= 3; i -= 2){//每边中间,有2先用2 step ++; if(!q2.empty()){ a = q2.front(), q2.pop(); b = q2.front(), q2.pop(); arr[n/2+1][1+step] = a; arr[n/2+1][n-step] = a; arr[1+step][n/2+1] = b; arr[n-step][n/2+1] = b; continue; } if(q4.empty()){flag=1;return;} cur = q4.front(), q4.pop(); arr[n/2+1][1+step] = cur; arr[n/2+1][n-step] = cur; arr[1+step][n/2+1] = cur; arr[n-step][n/2+1] = cur; } r0();//再去跑偶数 } void solve(){ if(n%2==0)r0();//偶数 if(n%2==1)r1();//奇数 run(); } int main(){ ios::sync_with_stdio(false); cin >> n; for(int i = 1; i <= n*n; i ++){ cin >> k; mp[k] ++; } for(auto it : mp){ while(it.second>=4){ q4.push(it.first); it.second -= 4; } while(it.second>=2){ q2.push(it.first); it.second -= 2; } while(it.second>=1){ q1.push(it.first); it.second -= 1; } //将4,2,1都存入队列 } solve(); return 0; }
最新回复(0)