题目链接:
http://poj.org/problem?id=3281
题意:
解法:
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 1010;
const int maxm = 510010;
const int inf = 0x3f3f3f3f;
struct G
{
int v, cap, next;
G() {}
G(int v, int cap, int next) : v(v), cap(cap), next(next) {}
} E[maxm];
int p[maxn], T;
int d[maxn], temp_p[maxn], qw[maxn]; //d顶点到源点的距离标号,temp_p当前狐优化,qw队列
void init()
{
memset(p, -1, sizeof(p));
T = 0;
}
void add(int u, int v, int cap)
{
E[T] = G(v, cap, p[u]);
p[u] = T++;
E[T] = G(u, 0, p[v]);
p[v] = T++;
}
bool bfs(int st, int en, int n)
{
int i, u, v, head, tail;
for(i = 0; i <= n; i++) d[i] = -1;
head = tail = 0;
d[st] = 0;
qw[tail] = st;
while(head <= tail)
{
u = qw[head++];
for(i = p[u]; i + 1; i = E[i].next)
{
v = E[i].v;
if(d[v] == -1 && E[i].cap > 0)
{
d[v] = d[u] + 1;
qw[++tail] = v;
}
}
}
return (d[en] != -1);
}
int dfs(int u, int en, int f)
{
if(u == en || f == 0) return f;
int flow = 0, temp;
for(; temp_p[u] + 1; temp_p[u] = E[temp_p[u]].next)
{
G& e = E[temp_p[u]];
if(d[u] + 1 == d[e.v])
{
temp = dfs(e.v, en, min(f, e.cap));
if(temp > 0)
{
e.cap -= temp;
E[temp_p[u] ^ 1].cap += temp;
flow += temp;
f -= temp;
if(f == 0) break;
}
}
}
return flow;
}
int dinic(int st, int en, int n)
{
int i, ans = 0;
while(bfs(st, en, n))
{
for(i = 0; i <= n; i++) temp_p[i] = p[i];
ans += dfs(st, en, inf);
}
return ans;
}
//最大流
int n, f, D;
int source, sink;
int main()
{
while(~scanf("%d%d%d", &n, &f, &D)){
init();
source = 0, sink = 2+f+D+2*n;
for(int i=1; i<=f; i++){
add(source, i, 1);
}
for(int i=1; i<=D; i++){
add(2*n+f+i, sink, 1);
}
for(int i=1; i<=n; i++){
add(f+i, f+i+n, 1);
int dish, drink;
scanf("%d%d", &dish,&drink);
for(int j=1;j<=dish;j++){
int x;
scanf("%d", &x);
add(x,f+i,1);
}
for(int j=1;j<=drink;j++){
int x;
scanf("%d", &x);
add(f+n+i, f+2*n+x, 1);
}
}
int ans = dinic(source, sink, sink+1);
printf("%d\n", ans);
}
return 0;
}