POJ-3281-Dining(网络流, 拆点)
作者:互联网
链接:
https://vjudge.net/problem/POJ-3281
题意:
农夫为他的 N (1 ≤ N ≤ 100) 牛准备了 F (1 ≤ F ≤ 100)种食物和 D (1 ≤ D ≤ 100) 种饮料。每头牛都有各自喜欢的食物和饮料,而每种食物或饮料只能分配给一头牛。最多能有多少头牛可以同时得到喜欢的食物和饮料?
思路:
建图,s->食物->牛前->牛后->饮料->汇点.
开始不知道把牛放中间,看了题解,先把食物给牛,在让牛去找饮料.给牛拆点是让牛只能选一个.
在跑最大流即可.
代码:
#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;
}
标签:int,res,cap,Dining,edges,Dgree,POJ,include,3281 来源: https://www.cnblogs.com/YDDDD/p/11298003.html