— 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.
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 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
解法:
1 #include <iostream>
2 #include<string.h>
3 #include<stdio.h>
4
5 using namespace std;
6
7 const int MAX = 30 +19;
8 int Map[MAX][MAX],a[MAX];
9 int L,W,n;
10 int pand(int x,int y,int i)
11 {
12 if(Map[x-1][y]==i) return 0;
13 if(Map[x][y-1]==i) return 0;
14 return 1;
15 }
16 int DFS(int x,int y)
17 {
18 if(x>L)
19 return 1;
20
21 for(int i=1;i<=n;i++)
22 if(((L-x)*W+W-y+2)/2<a[i])
23 return 0;
24
25 for(int i=1;i<=n;i++)
26 {
27 int TX=0;
28 if(a[i]&&pand(x,y,i)){
29 Map[x][y]=i;
30 a[i]--;
31 if(y==W)
32 TX = DFS(x+1,1);
33 else
34 TX = DFS(x,y+1);
35 a[i]++;
36 }
37 if(TX)
38 return 1;
39 }
40 return 0;
41 }
42 int main()
43 {
44 int N0=0,N;
45 cin>>N;
46 while(N--)
47 {
48 memset(a,0,sizeof(a));
49 memset(Map,0,sizeof(Map));
50
51 cin>>L>>W>>n;
52 for(int i=1;i<=n;i++)
53 cin>>a[i];
54 cout<<"Case #"<<++N0<<":"<<endl;
55
56 if(DFS(1,1))
57 {
58 cout<<"YES"<<endl;
59 for(int i=1;i<=L;i++)
60 {
61 cout<<Map[i][1];
62 for(int j=2;j<=W;j++)
63 {
64 cout<<" "<<Map[i][j];
65 }
66 cout<<endl;
67 }
68 }
69 else
70 cout<<"NO"<<endl;
71 }
72 return 0;
73 }