题意:
给你n*m的方格,你要用k种颜色去填,每种颜色要填ci次,并且要保证没有任意两个相邻的格子有相同的颜色,构造一种可行方法。
思路:
直接暴力回溯+剪枝,当没填的颜色中同种颜色数量超过(剩余格子+1)/2的时候,不可能合法。
代码:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define mem(a) memset(a,0,sizeof(a))
#define mp(x,y) make_pair(x,y)
const int INF = 0x3f3f3f3f;
const ll INFLL = 0x3f3f3f3f3f3f3f3fLL;
inline ll read(){
ll x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
//
const int maxn = 1e5+10;
int n,m,k,c[30];
int mp[10][10],flag;
int dx[4] = {0,0,1,-1};
int dy[4] = {1,-1,0,0};
bool ok(int x,int y,int col){
for(int i=0; i<4; i++){
int tx=x+dx[i],ty=y+dy[i];
if(tx<0 || tx>=n || ty<0 || ty>=m) continue;
if(mp[tx][ty] == col) return false;
}
return true;
}
void dfs(int sta){
if(flag) return ;
if(sta == n*m){
flag = true;
puts("YES");
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
cout << mp[i][j];
if(j==m-1) cout << endl;
else cout << " ";
}
}
return ;
}
int ma=-1;
for(int i=1; i<=k; i++) ma = max(ma,c[i]);
if(ma>(n*m-sta+1)/2) return ;
int x=sta/m,y=sta%m;
for(int i=1; i<=k; i++){
if(c[i]==0) continue;
if(ok(x,y,i)){
mp[x][y] = i;
c[i]--;
dfs(sta+1);
mp[x][y] = -1;
c[i]++;
}
}
}
int main(){
int T=read();
for(int cas=1; cas<=T; cas++){
memset(mp,-1,sizeof(mp));
flag = 0;
n=read(),m=read(),k=read();
for(int i=1; i<=k; i++)
c[i] = read();
cout << "Case #" << cas << ":\n";
dfs(0);
if(!flag) puts("NO");
}
return 0;
}