Poj - 3281 Dining (网络流-Ford-Fulkerson)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_41156591/article/details/81911374

题目链接

题意:求最多满意的牛数(同时有喜欢的food和drink).

题解:网络流建图然后套模板(最大流Ford-Fulkerson模板O(|F||E|) )

//左牛:0~n-1   右牛:n~2n-1

//food:2n~2n+F-1   drink:2n+F~2n+F+D-1

//S=2n+F+D       T=S+1 

代码如下:

#include<iostream>
#include<cstring>
#include<string>
#include<cstdio>
#include<cmath>
#include<vector>
#include<queue>
#include<map>
#include<algorithm>
using namespace std;
#define ll long long
#define inf 0x3f3f3f3f
const int maxn = 2e5 + 50;
struct edge {
	int to, cap, rev;//终点,容量,反向边序号
};
vector<edge>G[maxn];
bool used[maxn];
void add(int from, int to, int cap) {//向图中增加一条从from到to的容量为cap的边
	edge ee;
	ee.to = to, ee.cap = cap, ee.rev = G[to].size();
	G[from].push_back(ee);
	ee.to = from, ee.cap = 0, ee.rev = G[from].size() - 1;
	G[to].push_back(ee);
}
int dfs(int v, int t, int f) { //通过DFS寻找增广路
	if (v == t)return f;
	used[v] = true;
	for (int i = 0; i < G[v].size(); i++) {//iter[v]随i的变化而改变
		edge &e = G[v][i];
		if (!used[e.to] && e.cap>0) {
			int d = dfs(e.to, t, min(f, e.cap));
			if (d > 0) {
				e.cap -= d;
				G[e.to][e.rev].cap += d;
				return d;
			}
		}
	}
	return 0;
}





int max_flow(int s, int t) {
	int flow = 0;
	for (;;) {
		memset(used, 0, sizeof(used));
		int f = dfs(s, t, inf);
		if (f == 0)return flow;
		flow += f;
	}
}
void init(int n) {
	for (int i = 0; i <= n; i++)
		G[i].clear();
}
int main() {
	int n, F, D, f, d, x;
	while (~scanf("%d%d%d", &n, &F, &D)) {
		init(n);//多组数据记得清空
		int s = 2 * n + F + D, t = s + 1;
		for (int i = 0; i < F; i++)//S->food
			add(s, 2 * n + i, 1);
		for (int i = 0; i < n; i++)//牛->牛
			add(i, i + n, 1);
		for (int i = 0; i < D; i++)//drink->T
			add(2 * n + F + i, t, 1);
		for (int i = 0; i < n; i++) {
			scanf("%d%d", &f, &d);
			while (f--) {
				scanf("%d", &x);
				add(2 * n + x - 1, i, 1);//food->左牛
			}
			while (d--) {
				scanf("%d", &x);
				add(i + n, 2 * n + F + x - 1, 1); //右牛->drink
			}
		}
		printf("%d\n", max_flow(s, t));
	}
	return 0;
}


 

阅读更多

没有更多推荐了,返回首页