很有趣的搜索题。
将每个矩阵作为一个顶点,矩阵i在矩阵j的上方就从i到j连边,并且记录每个顶点的入度。
Dfs一个矩阵时,将它下方的矩阵入度减一,入度为0时即可以涂色的位置。
特么这题输入的是y和x!
#include <cstdio>
#include <cstring>
struct Rectangle {
int lx, ly, rx, ry, color;
};
Rectangle rect[20];
int edge[20][20];
int degree[20];
bool vis[20];
int n;
int ans;
void Dfs(int cnt, int color, int brush) {
if (brush >= ans) {
return;
}
if (cnt == n) {
ans = brush;
return;
}
for (int i = 0; i < n; i++) {
if (!vis[i] && degree[i] == 0) {
vis[i] = true;
for (int j = 0; j < n; j++) {
if (edge[i][j]) {
degree[j]--;
}
}
if (rect[i].color == color) {
Dfs(cnt + 1, rect[i].color, brush);
} else {
Dfs(cnt + 1, rect[i].color, brush + 1);
}
//回溯
vis[i] = false;
for (int j = 0; j < n; j++) {
if (edge[i][j]) {
degree[j]++;
}
}
}
}
}
int main()
{
int m;
scanf("%d", &m);
while (m--) {
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d%d%d%d%d", &rect[i].ly, &rect[i].lx,
&rect[i].ry, &rect[i].rx, &rect[i].color);
}
//建图
memset(edge, 0, sizeof(edge));
memset(degree, 0, sizeof(degree));
memset(vis, 0, sizeof(vis));
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == j) {
continue;
}
if (rect[i].ry <= rect[j].ly) {
if ((rect[j].lx <= rect[i].lx && rect[i].lx < rect[j].rx) ||
(rect[i].lx <= rect[j].lx && rect[j].rx <= rect[i].rx) ||
(rect[i].lx < rect[j].lx && rect[j].lx <= rect[i].rx)) {
edge[i][j] = 1;
degree[j]++;
}
}
}
}
ans = n;
Dfs(0, 0, 0);
printf("%d\n", ans);
}
return 0;
}