ZOJ 3209 Treasure Map(DLX精确覆盖)

ZOJ 3209 Treasure Map

题目链接

题意:给一个大矩形和一些小矩形,问最少几个矩形能覆盖大矩形,不能重复

思路:dlx精确覆盖,以每个矩形个格点为列,以每个小矩形为行,做精确覆盖即可

代码:

#include 
#include 

using namespace std;

const int MAXNODE = 450005;
const int MAXN = 505;
const int MAXM = 905;

const int INF = 0x3f3f3f3f;

struct DLX {

    int n, m, size;

    int U[MAXNODE], D[MAXNODE], R[MAXNODE], L[MAXNODE], row[MAXNODE], col[MAXNODE];
    int H[MAXN], S[MAXM];
    int ansd, ans[MAXN];

    void init(int n, int m) {
		this->n = n;
		this->m = m;
		ansd = INF;
        for(int i = 0; i <= m; i++) {
            S[i] = 0;
            U[i] = D[i] = i;
            L[i] = i - 1;
            R[i] = i + 1;
        }
        R[m] = 0; L[0] = m;
        size = m;
        for(int i = 1; i <= n; i++)
            H[i] = -1;
    }

    void Link(int r, int c) {
        ++S[col[++size] = c];
        row[size] = r;
        D[size] = D[c];
        U[D[c]] = size;
        U[size] = c;
        D[c] = size;
        if(H[r] < 0) H[r] = L[size] = R[size] = size;
        else {
            R[size] = R[H[r]];
            L[R[H[r]]] = size;
            L[size] = H[r];
            R[H[r]] = size;
        }
    }

    void remove(int c) {
        L[R[c]] = L[c]; R[L[c]] = R[c];
        for(int i = D[c]; i != c; i = D[i]) {
            for(int j = R[i]; j != i; j = R[j]) {
                U[D[j]] = U[j];
                D[U[j]] = D[j];
                --S[col[j]];
            }
		}
    }

    void resume(int c) {
        for(int i = U[c]; i != c; i = U[i])
            for(int j = L[i]; j != i; j = L[j])
                ++S[col[U[D[j]] = D[U[j]] = j]];
        L[R[c]] = R[L[c]] = c;
    }

    void Dance(int d) {
        if(ansd <= d) return;
        if(R[0] == 0) {
            if(d < ansd) ansd = d;
            return;
        }
        int c = R[0];
        for(int i = R[0]; i != 0; i = R[i]) {
            if(S[i] < S[c])
                c = i;
		}
        remove(c);
        for(int i = D[c]; i != c; i = D[i]) {
            for(int j = R[i]; j != i; j = R[j]) remove(col[j]);
            Dance(d + 1);
            for(int j = L[i]; j != i; j = L[j]) resume(col[j]);
        }
        resume(c);
    }
} gao;

int T, n, m, p;

int main() {
	scanf("%d", &T);
	while (T--) {
		scanf("%d%d%d", &n, &m, &p);
		gao.init(p, n * m);
		int x1, y1, x2, y2;
		for (int i = 1; i <= p; i++) {
			scanf("%d%d%d%d", &x1, &y1, &x2, &y2);
			for (int x = x1; x < x2; x++) {
				for (int y = y1; y < y2; y++) {
					gao.Link(i, x * m + y + 1);
				}
			}
		}
		gao.Dance(0);
		if (gao.ansd == INF) gao.ansd = -1;
		printf("%d\n", gao.ansd);
	}
    return 0;
}


你可能感兴趣的:(数据结构-DLX)