In mathematics, the four color theorem, or the four color map theorem, states that, given any separation of a plane into contiguous regions, producing a figure called a map, no more than four colors are required to color the regions of the map so that no two adjacent regions have the same color.
— Wikipedia, the free encyclopedia
In this problem, you have to solve the 4-color problem. Hey, I’m just joking.
You are asked to solve a similar problem:
Color an N × M chessboard with K colors numbered from 1 to K such that no two adjacent cells have the same color (two cells are adjacent if they share an edge). The i-th color should be used in exactly c i cells.
Matt hopes you can tell him a possible coloring.
Input
The first line contains only one integer T (1 ≤ T ≤ 5000), which indicates the number of test cases.
For each test case, the first line contains three integers: N, M, K (0 < N, M ≤ 5, 0 < K ≤ N × M ).
The second line contains K integers c i (c i > 0), denoting the number of cells where the i-th color should be used.
It’s guaranteed that c 1 + c 2 + · · · + c K = N × M .
Output
For each test case, the first line contains “Case #x:”, where x is the case number (starting from 1).
In the second line, output “NO” if there is no coloring satisfying the requirements. Otherwise, output “YES” in one line. Each of the following N lines contains M numbers seperated by single whitespace, denoting the color of the cells.
If there are multiple solutions, output any of them.
Sample Input
4 1 5 2 4 1 3 3 4 1 2 2 4 2 3 3 2 2 2 3 2 3 2 2 2
Sample Output
Case #1: NO Case #2: YES 4 3 4 2 1 2 4 3 4 Case #3: YES 1 2 3 2 3 1 Case #4: YES 1 2 2 3 3 1
题意:
给 大小为n*m的网格,有K种颜色,让你把第i 种颜色涂到Ci个网格中,其中有共同边的网格不能涂同一种颜色,问你是否能成功涂满,能就输出颜色,不能就输出NO
思路很简单,一开始把所有的网格都初始化为-1,在(1,1)这个位置开始搜,在(n,m)结束,在搜索的时候能涂颜色把颜色赋值给s[x][y]=i;颜色的个数减一,同时判断是否有相邻的颜色,最重要的是剪枝 ,没有剪枝会超时(思路是参考大佬的的)。
代码:
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define ll long long
int f[110],s[20][20];
int n,m,k;
int flag;
void print()
{
printf("YES\n");
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
if(j==1)
printf("%d",s[i][j]+1);
else
printf(" %d",s[i][j]+1);
}
printf("\n");
}
}
int judge(int x,int y,int i)//判断相邻边是否有相同的颜色,
{ //因为是从左上角开始的 所以直接看上边和左边是否重复就行
if(s[x-1][y]==i) return 0;
if(s[x][y-1]==i) return 0;
return 1;
}
void dfs(int x,int y,int sum)
{
if(flag) return ;
if(sum==0)
{
flag=1;
print();
return ;
}
for(int i=0;i<k;i++)//剪枝
{
if(f[i]>(sum+1)/2)
return ;
}
for(int i=0;i<k;i++)
{
//printf("%d--\n",judge(x,y,i));
if(f[i]&&judge(x,y,i))
{
//printf("%d %d--\n",f[i],judge(x,y,i));
s[x][y]=i;
f[i]--;
if(y==m)
dfs(x+1,1,sum-1);
else
dfs(x,y+1,sum-1);
f[i]++;
s[x][y]=-1;
}
}
}
int main()
{
int t,c=1;
scanf("%d",&t);
while(t--)
{
flag=0;
scanf("%d%d%d",&n,&m,&k);
for(int i=0;i<k;i++)
scanf("%d",&f[i]);
memset(s,-1,sizeof(s));
printf("Case #%d:\n",c++);
dfs(1,1,n*m);
if(!flag)
printf("NO\n");
}
}