首页 > 代码库 > POJ 1149 PIGS(最大流)

POJ 1149 PIGS(最大流)

POJ 1149 PIGS

题目链接

题意:有n个猪圈,m个顾客,猪圈中一开始有一些猪,顾客轮流来(注意是有先后顺序的),然后每个顾客会开启一些猪圈,在开启的猪圈中最多买b只猪,之后可以任意把剩下的猪分配到开着的猪圈中,问最多能卖出几只猪

思路:这题的关键在于建模,由于顾客有先后顺序,假如后来的顾客会开启x门,前面一个顾客也会开启x门,那么前面顾客相当与可以分配给后面顾客,
所以建模的方式为,源点和每个猪圈连,容量为猪圈猪数,每个猪圈和第一个开的顾客连,如果后面有顾客会开这个猪圈,则和之前的顾客连边,然后每个顾客在连向汇点,容量为会买的猪数

代码:

#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;

const int MAXNODE = 1205;
const int MAXEDGE = 100005;

typedef int Type;
const Type INF = 0x3f3f3f3f;

struct Edge {
	int u, v;
	Type cap, flow;
	Edge() {}
	Edge(int u, int v, Type cap, Type flow) {
		this->u = u;
		this->v = v;
		this->cap = cap;
		this->flow = flow;
	}
};

struct Dinic {
	int n, m, s, t;
	Edge edges[MAXEDGE];
	int first[MAXNODE];
	int next[MAXEDGE];
	bool vis[MAXNODE];
	Type d[MAXNODE];
	int cur[MAXNODE];
	vector<int> cut;

	void init(int n) {
		this->n = n;
		memset(first, -1, sizeof(first));
		m = 0;
	}
	void add_Edge(int u, int v, Type cap) {
		edges[m] = Edge(u, v, cap, 0);
		next[m] = first[u];
		first[u] = m++;
		edges[m] = Edge(v, u, 0, 0);
		next[m] = first[v];
		first[v] = m++;
	}

	bool bfs() {
		memset(vis, false, sizeof(vis));
		queue<int> Q;
		Q.push(s);
		d[s] = 0;
		vis[s] = true;
		while (!Q.empty()) {
			int u = Q.front(); Q.pop();
			for (int i = first[u]; i != -1; i = next[i]) {
				Edge& e = edges[i];
				if (!vis[e.v] && e.cap > e.flow) {
					vis[e.v] = true;
					d[e.v] = d[u] + 1;
					Q.push(e.v);
				}
			}
		}
		return vis[t];
	}

	Type dfs(int u, Type a) {
		if (u == t || a == 0) return a;
		Type flow = 0, f;
		for (int &i = cur[u]; i != -1; i = next[i]) {
			Edge& e = edges[i];
			if (d[u] + 1 == d[e.v] && (f = dfs(e.v, min(a, e.cap - e.flow))) > 0) {
				e.flow += f;
				edges[i^1].flow -= f;
				flow += f;
				a -= f;
				if (a == 0) break;
			}
		}
		return flow;
	}

	Type Maxflow(int s, int t) {
		this->s = s; this->t = t;
		Type flow = 0;
		while (bfs()) {
			for (int i = 0; i < n; i++)
				cur[i] = first[i];
			flow += dfs(s, INF);
		}
		return flow;
	}

	void MinCut() {
		cut.clear();
		for (int i = 0; i < m; i += 2) {
			if (vis[edges[i].u] && !vis[edges[i].v])
				cut.push_back(i);
		}
	}
} gao;

const int N = 1005;
const int M = 105;

int n, m, pre[N], vis[M][M];

int main() {
	while (~scanf("%d%d", &n, &m)) {
		memset(pre, 0, sizeof(pre));
		gao.init(n + m + 2);
		int w;
		for (int i = 1; i <= n; i++) {
			scanf("%d", &w);
			gao.add_Edge(0, i, w);
		}
		int a, k, b;
		for (int i = 1; i <= m; i++) {
			scanf("%d", &a);
			while (a--) {
				scanf("%d", &k);
				if (!pre[k]) {
					pre[k] = i;
					gao.add_Edge(k, n + i, INF);
				} else {
					if (vis[pre[k]][i] == 0) {
						vis[pre[k]][i] = 1;
						gao.add_Edge(n + pre[k], n + i, INF);
					}
				}
			}
			scanf("%d", &b);
			gao.add_Edge(n + i, n + m + 1, b);
		}
		printf("%d\n", gao.Maxflow(0, n + m + 1));
	}
	return 0;
}


POJ 1149 PIGS(最大流)