Problem
acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3209
vjudge.net/contest/65998#problem/B
Meaning
要在 p 张矩形藏宝图碎片中选若干张,恰好铺满一张 n * m 的格子图,问最少需要几张。
Analysis
就是选若干张藏宝图,使得每个格子都有且只有被覆盖一次,就是精确覆盖问题:藏宝图当成行,每一个格子都当成一列,藏宝图能覆盖的格子就是 1,不能的就是 0。
相当于把二维的格子图压成一维的,link 的时候要算出每个格子位于哪一列,就要对格子按某种顺序排序。比如:
然后观察下坐标和格子编号的关系就知道怎么 link 了。
Source code
#include <cstdio>
#include <algorithm>
using namespace std;
const int N = 30, M = 30, P = 500, NUM = P*N*M + N*M + 1;
int up[NUM], down[NUM], left[NUM], right[NUM];
int row[NUM], col[NUM], head[P+1], sum[N*M+1];
int ans;
void link(int r, int c, int id)
{
row[id] = r;
col[id] = c;
up[id] = up[c];
down[id] = c;
up[c] = down[up[c]] = id;
++sum[c];
if(head[r] == -1)
head[r] = left[id] = right[id] = id;
else
{
left[id] = left[head[r]];
right[id] = head[r];
left[head[r]] = right[left[head[r]]] = id;
}
}
void remove(int c)
{
left[right[c]] = left[c];
right[left[c]] = right[c];
for(int i=down[c]; i!=c; i=down[i])
for(int j=right[i]; j!=i; j=right[j])
{
up[down[j]] = up[j];
down[up[j]] = down[j];
--sum[col[j]];
}
}
void resume(int c)
{
left[right[c]] = right[left[c]] = c;
for(int i=up[c]; i!=c; i=up[i])
for(int j=left[i]; j!=i; j=left[j])
{
up[down[j]] = down[up[j]] = j;
++sum[col[j]];
}
}
int dance(int cnt)
{
if(!right[0])
return cnt;
int c = right[0];
for(int i=right[c]; i; i=right[i])
if(sum[i] < sum[c])
c = i;
remove(c);
for(int i=down[c]; i!=c; i=down[i])
{
for(int j=right[i]; j!=i; j=right[j])
remove(col[j]);
if(int tmp = dance(cnt+1))
ans = min(ans, tmp); // 不直接return,继续求
for(int j=left[i]; j!=i; j=left[j])
resume(col[j]);
}
resume(c);
return 0;
}
int main()
{
int t;
scanf("%d", &t);
while(t--)
{
int n, m, p;
scanf("%d%d%d", &n, &m, &p);
for(int i=0; i<=n*m; ++i)
{
up[i] = down[i] = col[i] = i;
row[i] = sum[i] = 0;
left[i] = i - 1;
right[i] = i + 1;
}
left[0] = n * m;
right[n*m] = 0;
for(int i=1, id=n*m; i<=p; ++i)
{
head[i] = -1;
int x1, x2, y1, y2;
scanf("%d%d%d%d", &x1, &y1, &x2, &y2);
for(int j=x1; j<x2; ++j)
for(int k=y1+1; k<=y2; ++k)
link(i, j*m+k, ++id);
}
ans = p + 1;
dance(0);
if(ans <= p)
printf("%d\n", ans);
else
puts("-1");
}
return 0;
}