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
【前言】
二分匹配可以算是网络流的经典应用了。
于是完成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; }
相关文章推荐
- POJ 1274 The Perfect Stall 二分匹配||最大流(简单题)
- 二分匹配 最大的匹配数 (简单)
- POJ 3216 二分匹配(想到就简单的题) floyed求最短路+匈牙利最大匹配
- POJ3041《Asteroids》方法:匈牙利算法(最小点覆盖数==最大二分匹配数)
- poj 2446 Chessboard (最大二分匹配)
- zoj 1654 Place the Robots 最大二分匹配
- HDU 1151Air Raid 最小路径覆盖=n-最大匹配量 (第二道二分匹配)
- 最大二分匹配——pku1325
- HDU1083 最大二分匹配
- poj 3020 二分最大匹配
- [置顶] 白话二分匹配之最大匹配+附上hdu2063解题报告
- zzulioj 1918 【二分最大匹配】
- POJ 3020 最小路径覆盖 = 顶点数-最大匹配数 二分匹配
- hdu 1083 简单的二分匹配 Courses
- 最大流练习:Parking,二分匹配
- D唐纳德和他的数学老师(华师网络赛)(二分匹配,最大流)
- hdu1045 Fire Net(最大二分匹配)
- uva 10122 Mysterious Mountain && ZOJ 1231 Mysterious Mountain (二分+二部图最大匹配)
- 二分最大匹配(匈牙利算法+HK算法)
- 图算法之:匈牙利算法(最大二分匹配)