思路:
最直接的想法: 新建源点和汇点,每种食物和对应的牛连边,牛和对应的饮料连边,源点连向食物,饮料连向汇点。但是这样可能会导致多个流同时流过一头牛,需要对其进行限制,因此将每头牛拆为两个点,中间连一个容量为1的边。形成了源点到食物,食物到牛1,牛1到牛2 ,牛2 到饮料,饮料到汇点的图。然后求最大流。
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <vector>
#include <queue>
#define LL long long
using namespace std;
const int maxn = 10000 + 10;
const int INF = 100000000;
struct Edge
{
int from,to,cap,flow;
Edge(int u,int v,int c,int w):from(u),to(v),cap(c),flow(w){ }
};
int n , m , s , t;
vector<Edge> edges;
vector<int> G[maxn];
bool vis[maxn];
int d[maxn];
int cur[maxn];
void init()
{
for(int i=0;i<=n+1;i++)
G[i].clear();
edges.clear();
}
void AddEdge(int from,int to,int cap)
{
edges.push_back(Edge(from,to,cap,0));
edges.push_back(Edge(to,from,0,0));
int M = edges.size();
G[from].push_back(M-2);
G[to].push_back(M-1);
}
bool BFS()
{
memset(vis,0,sizeof(vis));
queue<int>Q;
Q.push(s);
d[s] = 0;
vis[s] = 1;
while(!Q.empty())
{
int x = Q.front();Q.pop();
for(int i=0;i<G[x].size();i++)
{
Edge& e = edges[G[x][i]];
if(!vis[e.to] && e.cap > e.flow)
{
vis[e.to] = 1;
d[e.to] = d[x] + 1;
Q.push(e.to);
}
}
}
return vis[t];
}
int DFS(int x,int a)
{
if(x == t || a == 0) return a;
int flow = 0 , f;
for(int &i = cur[x];i<G[x].size();i++)
{
Edge& e = edges[G[x][i]];
if(d[x] + 1 == d[e.to] && (f = DFS(e.to,min(a,e.cap-e.flow))) > 0)
{
e.flow += f;
edges[G[x][i]^1].flow -= f;
flow += f;
a -= f;
if(a == 0) break;
}
}
return flow;
}
int Maxflow()
{
int flow = 0;
while(BFS())
{
memset(cur,0,sizeof(cur));
flow += DFS(s,INF);
}
return flow;
}
int N , F, D;
int main()
{
while(scanf("%d%d%d",&N,&F,&D)!=EOF)
{
n = F + N + N + D ;
s = 0;t = n + 1;
init();
int f , d , tmp;
for(int i=1;i<=N;i++)
{
scanf("%d%d",&f,&d);
for(int j=1;j<=f;j++)
{
scanf("%d",&tmp);
AddEdge(tmp,F+i,1);
}
for(int j=1;j<=d;j++)
{
scanf("%d",&tmp);
AddEdge(F+N+i,F+2*N+tmp,1);
}
}
for(int i=1;i<=N;i++) AddEdge(F+i,F+N+i,1);
for(int i=1;i<=F;i++) AddEdge(0,i,1);
for(int i=1;i<=D;i++) AddEdge(F+2*N+i,t,1);
int cost = Maxflow() ;
printf("%d\n",cost);
}
return 0;
}