题目:http://poj.org/problem?id=3281
题意:有F种食物和D种饮料,每种食物或饮料只能供一头牛享用,且每头牛只享用一种食物和一种饮料。现在有n头牛,每头牛都有自己喜欢的食物种类列表和饮料种类列表,问最多能使几头牛同时享用到自己喜欢的食物和饮料
思路:建源点和汇点,把牛放中间,饮料和食物放在牛的两边。源点和饮料连边,容量为1,食物和汇点连边,容量为1。对于每头牛,要拆点,容量为1,确保每头牛只能选一次
#include
#include
#include
#include
#include
using namespace std;
const int N = 510;
const int INF = 0x3f3f3f3f;
struct edge
{
int to, cap, next;
}g[N*1000];
int iter[N], level[N], head[N];
int cnt;
void add_edge(int v, int u, int cap)
{
g[cnt].to = u, g[cnt].cap = cap, g[cnt].next = head[v], head[v] = cnt++;
g[cnt].to = v, g[cnt].cap = 0, g[cnt].next = head[u], head[u] = cnt++;
}
bool bfs(int s, int t)
{
memset(level, -1, sizeof level);
queue que;
level[s] = 0;
que.push(s);
while(! que.empty())
{
int v = que.front(); que.pop();
for(int i = head[v]; i != -1; i =g[i].next)
{
int u = g[i].to;
if(g[i].cap > 0 && level[u] < 0)
{
level[u] = level[v] + 1;
que.push(u);
}
}
}
return level[t] == -1;
}
int dfs(int v, int t, int f)
{
if(v == t) return f;
for(int &i = iter[v]; i != -1; i = g[i].next)
{
int u = g[i].to;
if(g[i].cap > 0 && level[v] < level[u])
{
int d = dfs(u, t, min(f, g[i].cap));
if(d > 0)
{
g[i].cap -= d, g[i^1].cap += d;
return d;
}
}
}
return 0;
}
int dinic(int s, int t)
{
int flow = 0, f;
while(true)
{
if(bfs(s, t)) return flow;
memcpy(iter, head, sizeof head);
while(f = dfs(s, t, INF), f > 0)
flow += f;
}
}
int main()
{
int n, f, d;
while(~ scanf("%d%d%d", &n, &f, &d))
{
cnt = 0;
memset(head, -1, sizeof head);
for(int i = 1; i <= f; i++) //源点和食物连边,容量1
add_edge(0, i, 1);
for(int i = 1; i <= d; i++) //饮料和汇点连边,容量1
add_edge(f + 2 * n + i, f + 2 * n + d + 1, 1);
for(int i = 1; i <= n; i++) //对牛拆点,容量1,确保每头牛只能选择一次
add_edge(f + i, f + n + i, 1);
for(int i = 1; i <= n; i++)
{
int t1, t2, a, b;
scanf("%d%d", &t1, &t2);
for(int j = 0; j < t1; j++)
{
scanf("%d", &a);
add_edge(a, f + i, 1); //食物和牛连边,容量1
}
for(int j = 0; j < t2; j++)
{
scanf("%d", &a);
add_edge(f + n + i, f + 2 * n + a, 1); //牛和饮料连边,容量1
}
}
printf("%d\n", dinic(0, f + 2 * n + d + 1));
}
return 0;
}