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.
InputThe first line contains only one integer T (1 ≤ T ≤ 5000), which indicates the number of test cases.
— 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.
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 .
OutputFor 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 2Sample 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
这个题明白哪里要剪枝的话就比较好写。
剪枝的地方是每种颜色剩余的数量必须小于等于(剩下格子数+1)/2
这个画画图就明白了。可是我就不知道怎么想到这一点的,而且不知道这一点为什么这么有效,加上剪枝才78ms,不加超时
#include <iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int mp[10][10];
int c[30];
int n,m,k;
int dfs(int x,int y)
{
if(x>=n)return 1;
int flag;
for(int i=1;i<=k;i++)
{
int res=(n-x-1)*m+m-y;
if(c[i]>(res+1)/2)return 0;
}
for(int i=1;i<=k;i++)
{
flag=0;
if(c[i]==0)continue;
if(mp[x-1][y]!=i&&mp[x][y-1]!=i)
{
c[i]--;
mp[x][y]=i;
if(y==m-1)
flag=dfs(x+1,0);
else
flag=dfs(x,y+1);
c[i]++;
}
if(flag)return 1;
}
return 0;
}
int main()
{
int t;
cin>>t;
int z=1;
while(t--)
{
cin>>n>>m>>k;
// memset(c,0,sizeof(c));
for(int i=1;i<=k;i++)
scanf("%d",&c[i]);
printf("Case #%d:\n",z++);
if(dfs(0,0))
{
printf("YES\n");
for(int i=0;i<n;i++)
{
for(int j=0;j<m-1;j++)
printf("%d ",mp[i][j]);
printf("%d\n",mp[i][m-1]);
}
}
else printf("NO\n");
}
return 0;
}