POJ 2987 Firing(最大权闭合)

POJ 2987 Firing

题目链接

题意:n个人,每个人被炒由于都会得到一个利益(可正可负),现在有一些下属关系,如果一个人被炒了,他的下属要一起炒掉,问怎么炒使得炒利益最大,炒的人最少

思路:最大权闭合的题,要处理最少,那么其实就是在求最小割分成两个集合的时候,尽量让点都到T集合去,那么只要从S进行一次dfs,遇到满流的边就停止,经过的点都给S,就是要炒掉的人了

代码:

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

const int MAXNODE = 5005;
const int MAXEDGE = 200005;

typedef long long Type;
const Type INF = 0x3f3f3f3f3f3f3f;

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;
	}

	int dfs(int u) {
		vis[u] = true;
		int ans = 1;
		for (int i = first[u]; i + 1; i = next[i]) {
			int v = edges[i].v;
			if (edges[i].flow == edges[i].cap) continue;
			if (vis[v]) continue;
			ans += dfs(v);
		}
		return ans;
	}

	void solve(Type tot) {
		Type ans = Maxflow(0, n - 1);
		memset(vis, false, sizeof(vis));
		printf("%d %lld\n", dfs(0) - 1, tot - ans);
	}
} gao;

typedef long long ll;

int n, m;
ll sum;

int main() {
	while (~scanf("%d%d", &n, &m)) {
		ll w;
		sum = 0;
		gao.init(n + 2);
		for (int i = 1; i <= n; i++) {
			scanf("%lld", &w);
			if (w < 0) gao.add_Edge(i, n + 1, -w);
			if (w > 0) {
				gao.add_Edge(0, i, w);
				sum += w;
			}
		}
		int u, v;
		while (m--) {
			scanf("%d%d", &u, &v);
			gao.add_Edge(u, v, INF);
		}
		gao.solve(sum);
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值