link:
https://vjudge.net/problem/POJ-3281
Meaning of the questions:
Farmer for his N (1 ≤ N ≤ 100) Cattle prepared F (1 ≤ F ≤ 100) kinds of food and D (1 ≤ D ≤ 100) kinds of drinks. Each cow has its own favorite foods and drinks, and each food or beverage can be assigned to a cow. How many head of cattle up to get favorite food and drink at the same time?
Ideas:
Construction Plan, s-> Food -> Bovine - -> Beverages - cattle before>.> Sink
. I do not know the cattle began to put the middle, saw the solution to a problem, first food to cattle, let the cows go to drink in cattle split point is to make cattle can only choose one.
in the run to maximum flow.
Code:
#include <iostream>
#include <cstdio>
#include <vector>
#include <memory.h>
#include <queue>
#include <set>
#include <map>
#include <algorithm>
#include <math.h>
#include <stack>
using namespace std;
typedef long long LL;
const int MAXN = 1e2+10;
const int INF = 1e9;
struct Edge
{
int from, to, cap;
Edge(int f, int t, int c):from(f), to(t), cap(c){};
};
vector<int> G[MAXN*5];
vector<Edge> edges;
int Dgree[MAXN*5];
int f, d, n, s, t;
void AddEdge(int from, int to, int cap)
{
edges.push_back(Edge(from, to, cap));
edges.push_back(Edge(to, from, 0));
G[from].push_back(edges.size()-2);
G[to].push_back(edges.size()-1);
}
bool Bfs()
{
memset(Dgree, -1, sizeof(Dgree));
queue<int> que;
que.push(s);
Dgree[s] = 0;
while (!que.empty())
{
int u = que.front();
que.pop();
for (int i = 0;i < G[u].size();i++)
{
Edge &e = edges[G[u][i]];
if (e.cap > 0 && Dgree[e.to] == -1)
{
Dgree[e.to] = Dgree[u]+1;
que.push(e.to);
}
}
}
return Dgree[t] != -1;
}
int Dfs(int u, int flow)
{
if (u == t)
return flow;
int res = 0;
for (int i = 0;i < G[u].size();i++)
{
Edge &e = edges[G[u][i]];
if (e.cap > 0 && Dgree[e.to] == Dgree[u]+1)
{
int tmp = Dfs(e.to, min(flow, e.cap));
res += tmp;
e.cap -= tmp;
flow -= tmp;
edges[G[u][i]^1].cap += tmp;
if (flow == 0)
break;
}
}
if (res == 0)
Dgree[u] = -1;
return res;
}
int Dinic()
{
int res = 0;
while (Bfs())
res += Dfs(s, INF);
return res;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
//n头牛,每头两个编号i*2-1, i*2
//食物编号,2*n+i
//水编号,2*n+f+i
//源点s = 0, t = 2*n+f+d+1
while (cin >> n >> f >> d)
{
s = 0, t = 2*n+f+d+1;
for (int i = s;i <= t;i++)
G[i].clear();
edges.clear();
for (int i = 1;i <= n;i++)
{
AddEdge(i*2-1, i*2, 1);
int ff, dd, node;
cin >> ff >> dd;
while (ff--)
{
cin >> node;
AddEdge(2*n+node, i*2-1, 1);
}
while (dd--)
{
cin >> node;
AddEdge(2*i, 2*n+f+node, 1);
}
}
for (int i = 1;i <= f;i++)
AddEdge(0, 2*n+i, 1);
for (int i = 1;i <= d;i++)
AddEdge(2*n+f+i, t, 1);
int res = Dinic();
cout << res << endl;
}
return 0;
}