您的位置:首页 > Web前端

POJ1274 The Perfect Stall 简单最大二分匹配

2011-07-22 21:12 369 查看
Problem Address:http://poj.org/problem?id=1274

【前言】

二分匹配可以算是网络流的经典应用了。
于是完成poj1273之后,找到了poj1274并A之。
二分匹配建立在简单网络流的基础上,很简单的一个思想。
所以与上一道题相比并没有太多的变化,代码也是差不多。

【思路】

把cow和stall分别看成左右的结点,把两种结点一起编号并设计其邻接矩阵。
其中只能从cow连接到stall。
增加两个结点,一个作为源点,一个作为汇点。
从源点出发连接每个cow。
从每个stall结点出发连接汇点。
形成一个具有(n+m+2)个元素的矩阵。
对这个矩阵进行网络流计算即可得出结果。

【代码】

参考:http://poj.org/problem?id=1273

#include <iostream>
using namespace std;

const int maxn = 400;
const int MAX = 99999999;

int map[maxn+5][maxn+5];
int pre[maxn+5];
int q[maxn*maxn];

void init_map(int size)
{
int i,j;
for (i=0; i<size; i++)
{
for (j=0; j<size; j++)
{
map[i][j] = 0;
}
}
}

bool bfs(int s, int t, int size)
{
int head, tail, u, v;
memset(pre, -1, sizeof(pre));
head = 1;
tail = 0;
q[tail] = s;
while(tail<head)
{
u = q[tail];
for (v=1; v<=size; v++)
{
if (pre[v]==-1 && map[u][v]>0)
{
pre[v] = u;
q[head] = v;
head++;
if (v==t)
return true;
}
}
tail++;
}
return false;
}

int solve(int s, int t, int size)
{
int u, v, inc, maxflow = 0;
while(bfs(s, t, size))
{
inc = MAX;
for (v=t; v!=s; v=u)
{
u = pre[v];
if (map[u][v]<inc)
inc = map[u][v];
}
for (v=t; v!=s; v=u)
{
u = pre[v];
map[u][v] -= inc;
map[v][u] += inc;
}
maxflow += inc;
}
return maxflow;
}

int main()
{
int n,m,s,e;
int i,j;
while(scanf("%d %d", &n, &m)!=EOF)
{
init_map(n+m+2);
for (i=1; i<=n; i++)
{
scanf("%d", &s);
for (j=0; j<s; j++)
{
scanf("%d", &e);
map[i][n+e] = 1;
}
}
for (i=1; i<=n; i++)
map[0][i] = 1;
for (i=n+1; i<=n+m; i++)
map[i][n+m+1] = 1;
printf("%d\n", solve(0, n+m+1, n+m+2));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: