1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
| #include<bits/stdc++.h> using namespace std;
int s, n; int cnt[12]; int mat[32][32];
bool can_place(int x, int y, int size){ if(x+size<=s && y+size<=s){ for(int i=0;i<size;++i){ for(int j=0;j<size;++j){ if(mat[x+i][y+j] != 0){ return false; } } } return true; } else{ return false; } }
void place(int x, int y, int size){ for(int i=0;i<size;++i){ for(int j=0;j<size;++j){ mat[x+i][y+i] = size; } } --cnt[size]; }
void unplace(int x, int y){ int size = mat[x][y]; for(int i=0;i<size;++i){ for(int j=0;j<size;++j){ mat[x+i][y+j] = 0; } } ++cnt[size]; }
pair<int, int> next_loc(int x, int y){ for(int i=x;i<s;++i){ for(int j=y;j<s;++j){ if(mat[i][j] == 0){ return make_pair(i, j); } } } return make_pair(-1, -1); }
bool dfs(int x, int y){ for(int i=10;i>=1;--i){ if(cnt[i]){ if(can_place(x, y, i)){ place(x, y, i); auto loc = next_loc(x, y); if(loc.first == -1 && loc.second == -1){ return true; } if(dfs(loc.first, loc.second)){ return true; } unplace(x, y); } } } return false; }
int main(){ ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
int t; cin>>t; while(t--){ cin>>s>>n; for(int i=0;i<n;++i){ int tmp; cin>>tmp; cnt[tmp]++; } cout<<(dfs(0, 0)? "YES": "NO")<<endl; } }
|