题意
传送门 POJ 3281
题解
参考白书做法。求牛和食物及饮料的最大匹配,使用 Dinic 算法。牛拆成 2 个节点,连一条容量为 1 的边;食物、饮料分别向牛的不同节点连容量为 1 的边;保证每头牛最多只匹配一对食物及饮料。
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <queue>
#include <vector>
#define min(a,b) (((a) < (b)) ? (a) : (b))
#define max(a,b) (((a) > (b)) ? (a) : (b))
#define abs(x) ((x) < 0 ? -(x) : (x))
#define INF 0x3f3f3f3f
#define delta 0.85
#define eps 1e-5
#define PI 3.14159265358979323846
using namespace std;
#define MAX_V 420
struct edge{
int to, cap, rev;
edge(int to, int cap, int rev) : to(to), cap(cap), rev(rev){}
};
vector<edge> G[MAX_V];
int level[MAX_V], iter[MAX_V];
void add_edge(int from, int to, int cap){
G[from].push_back(edge(to, cap, G[to].size()));
G[to].push_back(edge(from, 0, G[from].size() - 1));
}
void bfs(int s){
memset(level, -1, sizeof(level));
queue<int> que;
level[s] = 0;
que.push(s);
while(!que.empty()){
int v = que.front(); que.pop();
for(int i = 0; i < G[v].size(); i++){
edge &e = G[v][i];
if(e.cap > 0 && level[e.to] < 0){
level[e.to] = level[v] + 1;
que.push(e.to);
}
}
}
}
int dfs(int v, int t, int f){
if(v == t) return f;
for(int &i = iter[v]; i < G[v].size(); i++){
edge &e = G[v][i];
if(e.cap > 0 && level[v] < level[e.to]){
int d = dfs(e.to, t, min(f, e.cap));
if(d > 0){
e.cap -= d;
G[e.to][e.rev].cap += d;
return d;
}
}
}
return 0;
}
int max_flow(int s, int t){
int flow = 0;
for(;;){
bfs(s);
if(level[t] < 0) return flow;
memset(iter, 0, sizeof(iter));
int f;
while((f = dfs(s, t, INF)) > 0){
flow += f;
}
}
}
#define MAX_N 100
#define MAX_F 100
#define MAX_D 100
int N, F, D;
bool likeF[MAX_N][MAX_F], likeD[MAX_N][MAX_F];
void solve(){
int N2 = N * 2, s = N * 2 + F + D, t = s + 1;
for(int i = 0; i < F; i++) add_edge(s, N2 + i, 1);
for(int i = 0; i < D; i++) add_edge(N2 + F + i, t, 1);
for(int i = 0; i < N; i++){
add_edge(i, N + i, 1);
for(int j = 0; j < F; j++) if(likeF[i][j]) add_edge(N2 + j, i, 1);
for(int j = 0; j < D; j++) if(likeD[i][j]) add_edge(N + i, N2 + F + j, 1);
}
printf("%d\n", max_flow(s, t));
}
int main(){
while(~scanf("%d%d%d", &N, &F, &D)){
memset(likeD, 0, sizeof(likeD));
memset(likeF, 0, sizeof(likeF));
for(int v = 0; v < N * 2 + F + D + 2; v++) G[v].clear();
for(int i = 0; i < N; i++){
int f, d;
scanf("%d%d", &f, &d);
for(int j = 0; j < f; j++){
int f2;
scanf("%d", &f2);
likeF[i][f2 - 1] = 1;
}
for(int j = 0; j < d; j++){
int d2;
scanf("%d", &d2);
likeD[i][d2 - 1] = 1;
}
}
solve();
}
return 0;
}