题目链接:http://poj.org/problem?id=3281
题意:给你n头牛,F种吃的,D种喝的,每头牛对某些吃的喝的情有独钟,每种吃的 和 喝的 只能给一头牛,一头牛只能得到一
种吃的一种喝的,而且一头牛必须同时获得吃的和喝的 才能被满足 问最多有多少头牛可以满足
一个最大流模板题,不过建图容易出错,需要注意的是牛需要拆点就行了。
是一个二分匹配问题,不过是两个条件必须满足,所以牛 需要拆点。
#include <algorithm>
#include <vector>
#include <cstdio>
#include <queue>
#include <cstring>
#include <iostream>
using namespace std;
const int INF = 0x3f3f3f3f;
const int MAX = (1ll << 31) - 1;
const int mavn = 1e5+5;
const int maxn = 1e5+5;
#define ll long long
struct Edge{
int to;
int cap;
int rev;
Edge(){}
Edge(int to,int d,int c):to(to),cap(d),rev(c){}
} ;
vector<Edge> v[mavn];
int n, m, s, t,F,D;
void addEdge(int from, int to, int cap){
v[from].push_back(Edge(to, cap,v[to].size()));
v[to].push_back(Edge(from, 0,v[from].size()-1));//单向边置为零,无向边置为cap,不然会多加边
}
int d[mavn],cnt, cur[mavn];
int DFS(int u, int flow){
if (u == t || !flow) return flow;
int ans = 0, tmp_flow;
for (int& i = cur[u]; i < v[u].size(); i++){
int to = v[u][i].to;
if (d[to] == d[u] + 1 && v[u][i].cap > 0){
tmp_flow = DFS(to, min(flow, v[u][i].cap));
if(tmp_flow > 0) {
flow -= tmp_flow;
v[u][i].cap -= tmp_flow;
ans += tmp_flow;
v[to][v[u][i].rev].cap += tmp_flow;
if (!flow)
break;
}
}
}
if (!ans) d[u] = -1;
return ans;
}
bool BFS(){
for(int i=s;i<=t+10;i++) d[i] = -1;
queue<int> que;
que.push(s);
d[s] = 0;
int u, _new;
while (!que.empty()){
u = que.front();
que.pop();
for (int i = 0; i < v[u].size(); i++){
_new = v[u][i].to;
if (d[_new] == -1 && v[u][i].cap > 0){
d[_new] = d[u] + 1;
que.push(_new);
}
}
}
return (d[t] != -1);
}
int dinic(){
int max_flow = 0;
while (BFS()){
for(int i=s;i<=t+10;i++) cur[i] = 0;
int tt;
while((tt = DFS(s,MAX)) > 0) max_flow += tt;
}
return max_flow;
}
int T, x, y;
int main(){
while(scanf("%d%d%d",&n,&F,&D)!=EOF){
s = 0, t = 2*n+F+D+1;
for(int i=0;i<=t;i++) v[i].clear();
for(int i=1;i<=n;i++) {
scanf("%d%d",&x,&y);
addEdge(i,i+n,1);
while(x--) {
scanf("%d",&m);
addEdge(m+2*n,i,1);
}
while(y--) {
scanf("%d",&m);
addEdge(i+n,m+2*n+F,1);
}
}
for(int i=1;i<=F;i++) {
addEdge(s,i+2*n,1);
}
for(int i=1;i<=D;i++) {
addEdge(i+2*n+F,t,1);
}
printf("%d\n",dinic());
}
return 0;
}