POJ1691-Painting A Board

18 篇文章 0 订阅

很有趣的搜索题。
将每个矩阵作为一个顶点,矩阵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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值