Description
Cows are such finicky eaters. Each cow has a preference for certain foods and drinks, and she will consume no others.
Farmer John has cooked fabulous meals for his cows, but he forgot to check his menu against their preferences. Although he might not be able to stuff everybody, he wants to give a complete meal of both food and drink to as many cows as possible.
Farmer John has cooked F (1 ≤ F ≤ 100) types of foods and prepared D (1 ≤ D ≤ 100) types of drinks. Each of his N (1 ≤ N ≤ 100) cows has decided whether she is willing to eat a particular food or drink a particular drink. Farmer John must assign a food type and a drink type to each cow to maximize the number of cows who get both.
Each dish or drink can only be consumed by one cow (i.e., once food type 2 is assigned to a cow, no other cow can be assigned food type 2).
Input
Lines 2.. N+1: Each line i starts with a two integers Fi and Di, the number of dishes that cow i likes and the number of drinks that cow i likes. The next Fi integers denote the dishes that cow i will eat, and the Di integers following that denote the drinks that cow i will drink.
Output
Sample Input
4 3 3 2 2 1 2 3 1 2 2 2 3 1 2 2 2 1 3 1 2 2 1 1 3 3
Sample Output
3
问题概述:农场有n头牛,f个食物,d瓶饮料,每个牛都可以吃其中的部分食物,喝其中部分的饮料,为如何分配能够
满足尽可能多的牛?注意:每个食物或饮料只能提供给一头牛!
样例:输入第一行为n f d,后面紧跟n行,第i行前两个数分别为第i头牛吃的食物数量以及饮料数量
http://www.cnblogs.com/g0feng/archive/2012/05/29/2524749.html
注意:残余网络包括反相边!如果残留网络上找不到增广路径,则当前流为最大流;反之,如果当前流不为最大流,
则一定有增广路径
为什么网络流要建反向边?
因为原网络有些错误的增广路会导致最终无法得到最大流,而这些增广路可以通过残余网络被后面的BFS修改
复杂度:O(VE²)
#include<stdio.h>
#include<queue>
#include<string.h>
#include<algorithm>
using namespace std;
int dis, sink, n, f, d, link[408], road[408][408];
int Eksech()
{
int i, u;
dis = 100000;
memset(link, -1, sizeof(link));
queue<int> q;
q.push(0);
while(q.empty()==0) /*寻找增广路*/
{
u = q.front();
q.pop();
if(u==sink)
return 1;
for(i=1;i<=sink;i++)
{
if(link[i]==-1 && road[u][i])
{
dis = min(dis, road[u][i]);
link[i] = u;
q.push(i);
}
}
}
return 0;
}
int main(void)
{
int i, j, fm, dm, a, ans, x, pre;
while(scanf("%d%d%d", &n, &f, &d)!=EOF) /*如何建图:源点→食物→牛(左)→牛(右)→饮料→汇点,因为一一对应,所有边长度都为1*/
{
sink = f+d+2*n+1;
memset(road, 0, sizeof(road));
for(i=1;i<=n;i++)
{
scanf("%d%d", &fm, &dm);
for(j=1;j<=fm;j++)
{
scanf("%d", &a);
road[0][a] = 1; /*源点与每个食物建边*/
road[a][f+i] = 1; /*食物与对应的牛(左)建边*/
}
road[f+i][f+i+n] = 1; /*牛(左)与牛(右)建边*/
for(j=1;j<=dm;j++)
{
scanf("%d", &a);
road[f+2*n+a][f+2*n+d+1] = 1; /*每个饮料与汇点建边*/
road[f+n+i][f+2*n+a] = 1; /*牛(右)与对应的饮料建边*/
}
}
ans = 0;
while(Eksech()) /* EK算法,每次广搜得到一条增广路径,然后更新残留网络 */
{
ans += dis;
x = sink;
while(x!=0)
{
pre = link[x];
road[pre][x] -= dis; /*减少当前边容量*/
road[x][pre] += dis; /*增加反向边流量*/
x = pre;
}
}
printf("%d\n", ans);
}
return 0;
}