每一头牛只喜欢吃一些食品和饮料而别的一概不吃。农夫做了 ()种食品并准备了 ()种饮料。()头牛都以决定了是否愿意吃某种食物和喝某种饮料。
农夫想给每一头牛一种食品和一种饮料,使得尽可能多的牛得到喜欢的食物和饮料。
每一件食物和饮料只能由一头牛来用。
链接
题解
将一头牛拆成两个点 和 ,从每个食品向能吃它的牛的 点连一条边,从每头牛的 点向它能喝的饮料连一条边。
源点向每个食品连边,每个饮料向汇点连边。
边权均为 ,最大流即为答案。
代码
#include <cstdio>
#include <climits>
#include <queue>
#include <algorithm>
const int MAXN = 100;
const int MAXM = 100;
struct Node;
struct Edge;
struct Node {
Edge *e, *c;
int l;
} N[MAXN * 2 + MAXM * 2 + 2];
struct Edge {
Node *s, *t;
int f, c;
Edge *next, *r;
Edge(Node *s, Node *t, const int c) : s(s), t(t), f(0), c(c), next(s->e) {}
};
struct Dinic {
bool makeLevelGraph(Node *s, Node *t, const int n) {
for (int i = 0; i < n; i++) N[i].l = 0, N[i].c = N[i].e;
std::queue<Node *> q;
q.push(s);
s->l = 1;
while (!q.empty()) {
Node *v = q.front();
q.pop();
for (Edge *e = v->e; e; e = e->next) if (!e->t->l && e->f < e->c) {
e->t->l = v->l + 1;
if (e->t == t) return true;
else q.push(e->t);
}
}
return false;
}
int findPath(Node *s, Node *t, const int limit = INT_MAX) {
if (s == t) return limit;
for (Edge *&e = s->c; e; e = e->next) if (e->t->l == s->l + 1 && e->f < e->c) {
int f = findPath(e->t, t, std::min(limit, e->c - e->f));
if (f) {
e->f += f, e->r->f -= f;
return f;
}
}
return 0;
}
int operator()(const int s, const int t, const int n) {
int res = 0;
while (makeLevelGraph(&N[s], &N[t], n)) {
int f;
while ((f = findPath(&N[s], &N[t])) > 0) res += f;
}
return res;
}
} dinic;
inline void addEdge(const int s, const int t, const int c) {
N[s].e = new Edge(&N[s], &N[t], c);
N[t].e = new Edge(&N[t], &N[s], 0);
(N[s].e->r = N[t].e)->r = N[s].e;
}
int s, t;
int main() {
int n, m1, m2;
scanf("%d %d %d", &n, &m1, &m2);
const int s = 0, t = n * 2 + m1 + m2 + 1;
for (int i = 1; i <= n; i++) addEdge(i, i + n, 1);
for (int i = n + n + 1; i <= n + n + m1; i++) addEdge(s, i, 1);
for (int i = n + n + m1 + 1; i <= n + n + m1 + m2; i++) addEdge(i, t, 1);
for (int i = 1; i <= n; i++) {
int k1, k2;
scanf("%d %d", &k1, &k2);
for (int j = 0; j < k1; j++) {
int x;
scanf("%d", &x);
addEdge(n + n + x, i, 1);
}
for (int j = 0; j < k2; j++) {
int x;
scanf("%d", &x);
addEdge(i + n, n + n + m1 + x, 1);
}
}
int maxFlow = dinic(s, t, n * 2 + m1 + m2 + 2);
printf("%d\n", maxFlow);
return 0;
}