hdu5113 Black And White DFS+剪枝

27 篇文章 0 订阅

点击打开链接

题意:

给你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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值