奥赛一本通 1445 平板涂色

1445 平板涂色

题目大意

给平面上的一些矩形涂成固定颜色,每一次可以将相同颜色的区域全部染色,不需要相邻,但是必须保证所有紧靠它上方的矩形都已经涂色,求最少的涂色次数。

知识要点

深度优先搜索

解题思路

给已经涂色的区域打上标记,每次选择未涂色且满足要求的一个区域递归搜索即可。

参考代码

#include <bits/stdc++.h>
using namespace std;

struct {
    int x1, y1, x2, y2, c;
} B[16];
int n, ans, v[16];
bool check(int i) { //检查能否涂色
    for(int j = 1; j <= n; j++) {
        if(v[j] || B[i].y1 != B[j].y2) continue;

        if(B[i].x1 <= B[j].x1 && B[j].x1 <= B[i].x2) return 0;
        if(B[i].x1 <= B[j].x2 && B[j].x2 <= B[i].x2) return 0;
    }
    return 1;
}
void DFS(int k, int num, int c) { //涂色次数,已涂色区域,上次颜色
    if(k >= ans) return;
    if(num == n) ans = k;

    for(int i = 1; i <= n; i++) {
        if(!v[i] && check(i)) {
            v[i] = 1;
            if(B[i].c == c) DFS(k, num + 1, c); //和上次一起
            else DFS(k + 1, num + 1, B[i].c);
            v[i] = 0;
        }
    }
}
int main() {
    scanf("%d", &n);
    for(int i = 1; i <= n; i++)
        scanf("%d%d%d%d%d", &B[i].y1, &B[i].x1, &B[i].y2, &B[i].x2, &B[i].c);

    ans = n;
    DFS(0, 0, 0);
    printf("%d\n", ans);
    return 0;
}
posted @ 2026-09-12 16:46  萧西待水  阅读(18)  评论(0)    收藏  举报