Search
Question: first, give the side length of a large array, then give m small square arrays, and give the side length of each square matrix. Then, ask if you can put the small square matrix into a large array without overlap, in addition, the generous array is fully utilized without surplus.
The code for this question is not hard to write. The key is to find a strategy which is more valuable than the pruning of the search itself.
The strategy for placing a small square matrix is to place it on the top as much as possible, and then to the left as much as possible. Another strategy was wrong at the beginning. I wanted to sort the small square matrix first, put the big one first, and then put the small one. In this way, problems may occur during the placement process, the correct strategy is that, based on the current placement situation, it doesn't matter the size.
To meet the conditions that should be placed at the top left as much as possible, you need to record the status of the big policy
Col [I] indicates the number of consecutive cells occupied by column I from the top.
Note that each column is continuously occupied during the entire placement process and will not be disconnected. This requires proper processing during search pruning.
#include <iostream>#include <cstdio>#include <cstring>using namespace std;#define N 55#define M 15int n,m;int col[N],s[M];bool dfs(int mm){ if(mm >= m) return true; int Min = N , c = 0; for(int i=1; i<=n; i++) if(col[i] < Min) { Min = col[i]; c = i; } for(int i=1; i<=10; i++) if(s[i]) { bool ok = true; if( !(c+i-1 <= n && col[c]+i <= n) ) continue; for(int k = c; k <= c+i-1; k++) if(col[k] != col[c]) { ok = false; break; } if(!ok) continue; s[i]--; for(int k=c; k <= c+i-1; k++) col[k] += i; if(dfs(mm+1)) return true; s[i]++; for(int k=c; k <= c+i-1; k++) col[k] -= i; } return false;}int main(){ int cas; cin >> cas; while(cas--) { int x,sum = 0; cin >> n >> m; memset(s,0,sizeof(s)); for(int i=0; i<m; i++) { cin >> x; s[x]++; sum += x * x; } memset(col,0,sizeof(col)); if(sum != n * n || !dfs(0)) cout << "HUTUTU!" << endl; else cout << "KHOOOOB!" << endl; } return 0;}