您的位置:首页 > 其它

[codevs 1916] 负载平衡问题

2015-02-03 12:27 253 查看
http://codevs.cn/problem/1916/

题解:

我的思考过程:
样例:
5

17 9 14 16 4



负载平衡问题是一类问题,大意就像题目说的那样,是个很有用的网络流模型。《线性规划与网络流24题》里有对建模的概述:

首先求出所有仓库存货量平均值,设第i个仓库的盈余量为A[i],A[i] = 第i个仓库原有存货量 - 平均存货量。建立二分图,把每个仓库抽象为两个节点Xi和Yi。增设附加源S汇T。

//i表示供应,j表示需求。

1、如果A[i]>0,从S向Xi连一条容量为A[i],费用为0的有向边。 //可以供应的量

2、如果A[i]<0,从Yi向T连一条容量为-A[i],费用为0的有向边。//需求的量

//这就限制了总的流量

3、每个Xi向两个相邻顶点j,从Xi到Xj连接一条容量为无穷大,费用为1的有向边, //搬运过去后,后者(j)立刻满足供需平衡

从Xi到Yj连接一条容量为无穷大,费用为1的有向边。//暂时搬运过去,在后续操作中满足供需平衡

求最小费用最大流,最小费用流值就是最少搬运量。

代码:

总时间耗费: 15ms

总内存耗费: 256B

#include<cstdio>
#include<iostream>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;

const int maxn = 100 + 100 + 10;
const int INF = 1e9 + 7;

struct Edge {
	int from, to, cap, flow, cost;
};

int n, s, t, A[maxn];

vector<Edge> edges;
vector<int> G[maxn];

void AddEdge(int from, int to, int cap, int cost) {
	edges.push_back((Edge){from, to, cap, 0, cost});
	edges.push_back((Edge){to, from, 0, 0, -cost});
	int m = edges.size();
	G[from].push_back(m-2);
	G[to].push_back(m-1);
}

int d[maxn], p[maxn], a[maxn];
bool inq[maxn];

bool BellmanFord(int& cost) {
	for(int i = s; i <= t; i++) d[i] = INF;
	memset(inq, 0, sizeof(inq));
	d[s] = 0; inq[s] = 1; a[s] = INF; p[s] = 0;
	
	queue<int> Q;
	Q.push(s);
	while(!Q.empty()) {
		int x = Q.front(); Q.pop();
		inq[x] = 0;
		for(int i = 0; i < G[x].size(); i++) {
			Edge& e = edges[G[x][i]];
			if(e.cap > e.flow && d[e.to] > d[x] + e.cost) {
				d[e.to] = d[x] + e.cost;
				p[e.to] = G[x][i];
				a[e.to] = min(a[x], e.cap-e.flow);
				if(!inq[e.to]) { Q.push(e.to); inq[e.to] = 1; }
			}
		}
	}
	if(d[t] == INF) return 0;
	
	cost += a[t] * d[t];
	
	int x = t;
	while(x != s) {
		edges[p[x]].flow += a[t];
		edges[p[x]^1].flow -= a[t];
		x = edges[p[x]].from;
	}
	
	return 1;
}

void MincostMaxflow() {
	int cost = 0;
	while(BellmanFord(cost));
	cout << cost << endl;
}

int main() {
	cin >> n;
	s = 0; t = n + n + 1;
	
	int ave = 0;
	for(int i = 1; i <= n; i++) {
		cin >> A[i];
		ave += A[i];
	}
	ave /= n;
	
	for(int i = 1, j; i <= n; i++) {
		A[i] -= ave;
		if(A[i] > 0) AddEdge(s, i, A[i], 0);
		if(A[i] < 0) AddEdge(i+n, t, -A[i], 0);
		if((j = i-1) == 0) j = n; 
		AddEdge(i, j, INF, 1); AddEdge(i, j+n, INF, 1);
		if((j = i+1) > n) j = 1;
		AddEdge(i, j, INF, 1); AddEdge(i, j+n, INF, 1);
	}

	MincostMaxflow();
	
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: