题目
Alice and Bob often play games on chessboard. One day, Alice draws a board with size M * N. She wants Bob to use a lot of cards with size 1 * 2 to cover the board. However, she thinks it too easy to bob, so she makes some holes on the board (as shown in the figure below).
We call a grid, which doesn’t contain a hole, a normal grid. Bob has to follow the rules below:
- Any normal grid should be covered with exactly one card.
- One card should cover exactly 2 normal adjacent grids.
Some examples are given in the figures below:
A VALID solution.
An invalid solution, because the hole of red color is covered with a card.
An invalid solution, because there exists a grid, which is not covered.
Your task is to help Bob to decide whether or not the chessboard can be covered according to the rules above.
一个棋盘内,有些地方有洞,有些地方没有,没有洞的地方可以放东西,求是否可以用1*2的长方形填满所有格子(除了洞)。当然长方形不能相互覆盖。
第一行有3个整数:m, n, k (0 < m, n <= 32, 0 <= k < m * n),行数,列数和洞数。在接下来的k行中,每一行都有一对整数(x, y)表示第y行第x列上的一个孔。
题解
一个覆盖两个格子的长方形必然是两个相邻的格子,所以每个格子可以和它相邻的格子连线,然后又用黑白染色法把棋盘分为两部分,每相邻的格子不在同一部分,这时使用最大匹配,求出最大匹配数即最多可放的长方形数ans。
若ans*2=格子总数-洞数,那么“YES”,否则“NO”
代码
#include <cstdio>
#include <cstring>
using namespace std;
int n,m,k,cnt,e,ans;
int ls[550],ne[2200],y[2200],link[1050];
bool cover[1050],f[35][35];
int xz[6]={0,0,-1,1};
int yz[6]={-1,1,0,0};
bool dfs(int k){
for (int i=ls[k];i;i=ne[i])
if (!cover[y[i]]){
int t=link[y[i]];
link[y[i]]=k;
cover[y[i]]=1;
if (t==0||dfs(t)) return 1;
link[y[i]]=t;
}
return 0;
}
int main(){
scanf("%d%d%d",&n,&m,&k);
for (int i=1;i<=k;i++){
int a,b;
scanf("%d%d",&b,&a);
f[a][b]=1;
}
for (int i=1;i<=n;i++)
for (int j=1;j<=m;j++)
if ((i+j)%2==0&&!f[i][j]){
e++;
for (int k=0;k<4;k++){
int a=i+xz[k],b=j+yz[k];
if ((a>0)&&(a<=n)&&(b>0)&&(b<=m)&&!f[a][b])
ne[++cnt]=ls[e],ls[e]=cnt,y[cnt]=(a-1)*m+b;
}
}
for (int i=1;i<=e;i++){
memset(cover,0,sizeof(int)*(n*m+3));
if (dfs(i)) ans++;
}
if (ans*2==n*m-k) printf("YES\n");
else printf("NO\n");
}