— 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 icells.
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 3 1
没什么好说的,dfsdfsdfs
//#include <bits/stdc++.h> #include <iostream> #include <cstdio> #include <cmath> #include<cstring> #include <algorithm> #include <queue> using namespace std; typedef long long LL; const LL INF = 1e13; const int mod = 1000000007; const int mx = 1e7; //check the limits, dummy typedef pair<int, int> pa; //const double PI = acos(-1); //ll gcd(ll a, ll b) { return b ? gcd(b, a % b) : a; } #define swa(a,b) a^=b^=a^=b #define re(i,a,b) for(int i=(a),_=(b);i<_;i++) #define rb(i,a,b) for(int i=(b),_=(a);i>=_;i--) #define clr(a) memset(a, 0, sizeof(a)) #define lowbit(x) ((x)&(x-1)) //#define mkp make_pai void sc(int& x) { scanf("%d", &x); }void sc(int64_t& x) { scanf("%lld", &x); }void sc(double& x) { scanf("%lf", &x); }void sc(char& x) { scanf(" %c", &x); }void sc(char* x) { scanf("%s", x); } int n, m, k,ans; int a[mx],mp[55][55]; bool flag; bool dfs(int x, int y, int r) { if (!r) { flag = 1; return 1; } re(i, 1, k + 1)if (a[i] > (r + 1) / 2)return 0; re(i, 1, k + 1) { if (a[i]) { if (x && mp[x - 1][y] == i)continue; if (y && mp[x][y - 1] == i)continue; a[i]--; mp[x][y] = i; if (y < m - 1)dfs(x, y + 1, r - 1); else dfs(x + 1, 0, r - 1); if (flag)return 1; a[i]++; } } return 0; } int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); int T, cas = 1; scanf("%d", &T); while (T--) { clr(mp); flag = 0; sc(n), sc(m), sc(k); re(i, 1, k+1)sc(a[i]); printf("Case #%d:\n",cas++); if (!dfs(0, 0, n * m)) { puts("NO"); continue; } puts("YES"); re(i, 0, n)re(j, 0, m)printf(j == m - 1 ? "%d\n" : "%d ", mp[i][j]); } return 0; }