这题WA了两次。刚开始我建的图是: s→食物→牛→饮料→t ,但这样不能保证每头牛最多只得到一种食物和一种饮料,WA了。后来又想了一下,按照以下方式建图:s→食物→牛→牛→饮料→t,这样就能保证每头牛最多只得到一种食物和一种饮料。心想这回肯定能AC的,谁知提交上去还是一个WA。我又仔细检查了一下代码,惊奇的发现是数组开小了,这个真不应该~
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;
const int maxn = 500;
const int maxm = 21000;
const int oo = 1 << 30;
int idx;
int cur[maxn], pre[maxn];
int dis[maxn], gap[maxn];
int aug[maxn], head[maxn];
struct Node
{
int u, v, w;
int next;
}edge[maxm];
void addEdge(int u, int v, int w)
{
edge[idx].u = u;
edge[idx].v = v;
edge[idx].w = w;
edge[idx].next = head[u];
head[u] = idx++;
edge[idx].u = v;
edge[idx].v = u;
edge[idx].w = 0;
edge[idx].next = head[v];
head[v] = idx++;
}
int SAP(int s, int e, int n)
{
int max_flow = 0, v, u = s;
int id, mindis;
aug[s] = oo;
pre[s] = -1;
memset(dis, 0, sizeof(dis));
memset(gap, 0, sizeof(gap));
gap[0] = n; // 我觉得这一句要不要都行,因为dis[e]始终为0
for (int i = 0; i <= n; ++i)
{ // 初始化当前弧为第一条弧
cur[i] = head[i];
}
while (dis[s] < n)
{
bool flag = false;
if (u == e)
{
max_flow += aug[e];
for (v = pre[e]; v != -1; v = pre[v]) // 路径回溯更新残留网络
{
id = cur[v];
edge[id].w -= aug[e];
edge[id^1].w += aug[e];
aug[v] -= aug[e]; // 修改可增广量,以后会用到
if (edge[id].w == 0) u = v; // 不回退到源点,仅回退到容量为0的弧的弧尾
}
}
for (id = cur[u]; id != -1; id = edge[id].next)
{ // 从当前弧开始查找允许弧
v = edge[id].v;
if (edge[id].w > 0 && dis[u] == dis[v] + 1) // 找到允许弧
{
flag = true;
pre[v] = u;
cur[u] = id;
aug[v] = min(aug[u], edge[id].w);
u = v;
break;
}
}
if (flag == false)
{
if (--gap[dis[u]] == 0) break; /* gap优化,层次树出现断层则结束算法 */
mindis = n;
cur[u] = head[u];
for (id = head[u]; id != -1; id = edge[id].next)
{
v = edge[id].v;
if (edge[id].w > 0 && dis[v] < mindis)
{
mindis = dis[v];
cur[u] = id; // 修改标号的同时修改当前弧
}
}
dis[u] = mindis + 1;
gap[dis[u]]++;
if (u != s) u = pre[u]; // 回溯继续寻找允许弧
}
}
return max_flow;
}
int N, F, D;
int main()
{
while (scanf("%d %d %d", &N, &F, &D) != EOF)
{
memset(head, -1, sizeof(head));
idx = 0;
int a, b, f, d;
for (int i = 1; i <= N; ++i)
{
scanf("%d %d", &a, &b);
while (a--)
{
scanf("%d", &f);
addEdge(f, F + i, 1);
}
while (b--)
{
scanf("%d", &d);
addEdge(F + N + i, F + N + N + d, 1);
}
}
int source = 0, sink = N + N + F + D + 1;
int n = sink + 1;
for (int i = 1; i <= F; ++i)
addEdge(source, i, 1);
for (int i = 1; i <= N; ++i)
addEdge(F + i, F + N + i, 1);
for (int i = 1; i <= D; ++i)
addEdge(F + N + N + i, sink, 1);
printf("%d\n", SAP(source, sink, n));
}
return 0;
}