Chessboard
Description
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: 1. Any normal grid should be covered with exactly one card. 2. 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. Input
There are 3 integers in the first line: m, n, k (0 < m, n <= 32, 0 <= K < m * n), the number of rows, column and holes. In the next k lines, there is a pair of integers (x, y) in each line, which represents a hole in the y-th row, the x-th column.
Output
If the board can be covered, output "YES". Otherwise, output "NO".
Sample Input 4 3 2 2 1 3 3 Sample Output YES Hint ![]() A possible solution for the sample input. Source
POJ Monthly,charlescpp
|
【思路】
将棋盘像国际象棋棋盘那样分割为黑白块,那么用纸片覆盖时就可以视作匹配没有洞的黑块和白块,用匈牙利算法求二分图的最大匹配即可。具体可以这么建图,二分图的左右点集都是黑白块1到N*M,若黑块可能与周边白块相匹配,则从左点集对应的黑块与右点集对应的白块连一条线。跑一遍匈牙利算法后,看二倍最大匹配数是否等于N*M-K就好了。
【代码】
#include<cstdio>
#include<cstring>
#include<vector>
#include<algorithm>
using namespace std;
const int MAXN=100;
const int DIR[4][2]={{0,-1},{-1,0},{0,1},{1,0}};
int m,n,k;
bool visited[MAXN*MAXN];
bool hole[MAXN][MAXN];
int xmatch[MAXN*MAXN],ymatch[MAXN*MAXN];
vector<int> connect[MAXN];
bool dfs(int u)
{
for(int i=0;i<connect[u].size();i++){
int j=connect[u][i];
if(!visited[j]){
visited[j]=true;
if(ymatch[j]==-1||dfs(ymatch[j])){
xmatch[u]=j;
ymatch[j]=u;
return true;
}
}
}
return false;
}
int hungary()
{
int ans=0;
memset(xmatch,0xff,sizeof(xmatch));
memset(ymatch,0xff,sizeof(ymatch));
for(int i=1;i<=n*m;i++){
memset(visited,false,sizeof(visited));
if(dfs(i))ans++;
}
return ans;
}
int main()
{
memset(hole,false,sizeof(hole));
scanf("%d %d %d",&m,&n,&k);
for(int i=1;i<=k;i++){
int x,y;
scanf("%d %d",&x,&y);
hole[y][x]=true;
}
for(int i=1;i<=m;i++)
for(int j=1;j<=n;j++)
if(!hole[i][j])
for(int k=0;k<4;k++){
int y=i+DIR[k][0],x=j+DIR[k][1];
if(1<=y&&y<=m&&1<=x&&x<=n&&!hole[y][x]){
connect[(i-1)*n+j].push_back((y-1)*n+x);
}
}
if(hungary()==n*m-k)
printf("YES\n");
else
printf("NO\n");
return 0;
}