HDU 5113 dfs剪枝

时间:2023-12-23 11:49:44

题意:告诉格子规格,颜色个数,以及每个颜色能涂得格子数目,问是否能够实现相邻两个格子的颜色数目不相同。

分析:因为数据很小,格子最多是5 * 5大小的,因此可以dfs。TLE了一次之后开始剪枝,31ms过。剪枝看代码。

 #include <cstdio>
#include <iostream>
#include <sstream>
#include <cmath>
#include <cstring>
#include <cstdlib>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <algorithm>
using namespace std;
#define ll long long
#define _cle(m, a) memset(m, a, sizeof(m))
#define repu(i, a, b) for(int i = a; i < b; i++)
#define repd(i, a, b) for(int i = b; i >= a; i--)
#define sfi(n) scanf("%d", &n)
#define pfi(n) printf("%d\n", n)
#define MAXN 26
int n, m, k, tot;
int c[MAXN];
int mpp[][], re[][];
int tcc[MAXN];
void put(int mp[][])
{
repu(i, , n)
{
repu(j, , m)
if(j == )
printf("%d", mp[i][j]);
else printf(" %d", mp[i][j]);
puts("");
}
}
bool Judge(int tc[], int cur)///剪枝,剩下没染的颜色中的数目如果超过一半就break
{
repu(i, , k) if(c[i] - tc[i] > (tot - cur + ) / ) return true;
return false;
}
int debug(int cur,int mp[][])
{
cout<<cur<<endl;
put(mp);
}
bool dfs(int cur, int tc[], int mp[][])
{
///当前已经染得格子数目,当前染得每个颜色剩下的数目,当前的已经订好的方案
///debug(cur,mp);
if(cur >= n * m) return true;
int x = cur / m;
int y = cur - x * m;
if(Judge(tc, cur)) return false;
repu(i, , k)
{
if(tc[i] < c[i])
{
if(x - >= && mp[x - ][y] == i + )
continue;
if(y - >= && mp[x][y - ] == i + )
continue;
tc[i]++;
mp[x][y] = i + ;
if(dfs(cur + , tc, mp))
return true;
tc[i]--;
}
}
return false;
}
int main()
{
int T;
sfi(T);
repu(kase, , T + )
{
sfi(n), sfi(m), sfi(k);
tot = n * m;
repu(i, , k) sfi(c[i]);
_cle(tcc, );
_cle(mpp, );
printf("Case #%d:\n", kase);
if(dfs(, tcc, mpp))
{
printf("YES\n");
put(mpp);
}
else
printf("NO\n");
}
return ;
}