大意不在赘述。
思路:这是我有关图论的参考书上的一本书上的例题,我顺便把它写了一下。
具体的实现过程可以参考我的另一篇博客:http://blog.csdn.net/wall_f/article/details/8229629
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <string>
using namespace std;
const int MAXN = 10010;
const int MAXM = 400010;
const int INF = 0x3f3f3f3f;
struct Edge
{
int v, f;
int next;
}edge[MAXM];
int n, nf, nd;
int cnt;
int s, t;
int first[MAXN], level[MAXN];
int q[MAXN];
char str[3000];
void init()
{
cnt = 0;
memset(first, -1, sizeof(first));
}
void read_graph(int u, int v, int f)
{
edge[cnt].v = v, edge[cnt].f = f;
edge[cnt].next = first[u], first[u] = cnt++;
edge[cnt].v = u, edge[cnt].f = 0;
edge[cnt].next = first[v], first[v] = cnt++;
}
int bfs(int s, int t)
{
memset(level, 0, sizeof(level));
level[s] = 1;
int front = 0, rear = 1;
q[front] = s;
while(front < rear)
{
int x = q[front++];
if(x == t) return 1;
for(int e = first[x]; e != -1; e = edge[e].next)
{
int v = edge[e].v, f = edge[e].f;
if(!level[v] && f)
{
level[v] = level[x] + 1;
q[rear++] = v;
}
}
}
return 0;
}
int dfs(int u, int maxf, int t)
{
if(u == t) return maxf;
int ret = 0;
for(int e = first[u]; e != -1; e = edge[e].next)
{
int v = edge[e].v, f = edge[e].f;
if(level[v] == level[u] + 1 && f)
{
int Min = min(maxf-ret, f);
f = dfs(v, Min, t);
edge[e].f -= f;
edge[e^1].f += f;
ret += f;
if(ret == maxf) return ret;
}
}
return ret;
}
int Dinic(int s, int t)
{
int ans = 0;
while(bfs(s, t)) ans += dfs(s, INF, t);
return ans;
}
void read_case()
{
init();
s = 0, t = nf+nd+n+n+1;
for(int i = 1; i <= n; i++) //A,A1连一条边
{
int A = nf+nd+i, A1 = nf+nd+n+i;
read_graph(A, A1, 1);
}
for(int i = 1; i <= nf; i++) read_graph(s, i, 1); //源点与食物相连
for(int i = 1; i <= n; i++)
{
int f2, d2;
int A = nf+nd+i, A1 = nf+nd+n+i; //拆点为A,A1
scanf("%d%d", &f2, &d2);
while(f2--)
{
int v;
scanf("%d", &v);
read_graph(v, A, 1); //食物与A
}
while(d2--)
{
int v;
scanf("%d", &v);
read_graph(A1, v+nf, 1); //A1与饮料
}
}
for(int i = 1; i <= nd; i++) read_graph(i+nf, t, 1); //汇点与饮料相连
}
void solve()
{
read_case();
int ans = Dinic(s, t);
printf("%d\n", ans);
}
int main()
{
while(~scanf("%d%d%d", &n, &nf, &nd))
{
solve();
}
return 0;
}