您的位置:首页 > 其它

POJ 2446 : Chessboard(二部图算法)

2016-12-17 01:19 477 查看
可以将棋盘看成国际象棋的棋盘,也就是说,相邻两格的颜色不同,设为白色和黑色.那么白色格子和黑色格子就构成了一个二部图,只能在异色格子之间连线.现在就是要求完美二部图匹配,判断最后的最大匹配数是否等于没有洞的格子数.这里我用邻接链表来当存储结构,节省了很大空间开销.

总时间限制:
2000ms
内存限制:
65536kB

描述
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.

输入
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.
输出
If the board can be covered, output “YES”. Otherwise, output “NO”.
样例输入
4 3 2
2 1
3 3

样例输出
YES

提示



A possible solution for the sample input.
来源
POJ Monthly,charlescpp

查看

提交

统计

提示

提问

#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;

int n, m, k, x, y, res;
int map[40][40], vis[1200], mat[1200];

int change(int i,int j)
{
return j+(i-1)*n;
}

struct node
{
int num;
node *next;
node(){
next = NULL;
}
};

struct LIST//邻接表
{
int num;
node *next;
void append(int val)
{
node *t = new node;
t->num = val;
t->next = next;
next = t;
}
}l[1600];

int find(int val)
{
node *temp = l[val].next;
while(temp)
{
if(vis[temp->num] == 0)
{
vis[temp->num] = 1;
if(!mat[temp->num] || find(mat[temp->num]))
{
mat[temp->num] = val;
return 1;
}
}
temp = temp->next;
}
return 0;
}

void hungary()
{
for(int i=1;i<=m*n;i++)
{
if(l[i].next)
{
res += find(i);
memset(vis,0,sizeof(vis));
}
}
}

int main()
{
scanf("%d%d%d",&m,&n,&k);
for(int i=0;i<k;i++)
{
scanf("%d%d",&x,&y);
map[y][x] = -1;//第 y 行,第 x 列
}

for(int i=1;i<=m;i++)//完成邻接表的构建
for(int j=1;j<=n;j++)
{
if(map[i][j] != -1)
{
int temp = change(i,j);
//左
if(i-1>=1 && map[i-1][j]!=-1)
l[temp].append(change(i-1,j));
//右
if(i+1<=m && map[i+1][j]!=-1)
l[temp].append(change(i+1,j));
//上
if(j-1>=1 && map[i][j-1]!=-1)
l[temp].append(change(i,j-1));
//下
if(j+1<=n && map[i][j+1]!=-1)
l[temp].append(change(i,j+1));
}
}

hungary();

if(res == m*n-k)
printf("YES\n");
else
printf("NO\n");
//cout<<res<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  poj 算法