您的位置:首页 > 其它

最小费用最大流入门

2015-07-27 11:21 295 查看
poj 3281

学会建图啊。。 啊。。 啊。。

S(0)-食物(2n+i)-牛1(i)-牛2(n+i)-饮料(2n+F+i)-T(2n+F+D+1)

/*Author :usedrose  */
/*Created Time :2015/7/27 15:20:54*/
/*File Name :2.cpp*/
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <cstdlib>
#include <cstring>
#include <climits>
#include <vector>
#include <string>
#include <ctime>
#include <cmath>
#include <deque>
#include <queue>
#include <stack>
#include <set>
#include <map>
#define INF 0x3f3f3f3f
#define eps 1e-8
#define pi acos(-1.0)
#define MAXN 2010
#define OK cout << "ok" << endl;
#define o(a) cout << #a << " = " << a << endl
#define o1(a,b) cout << #a << " = " << a << "  " << #b << " = " << b << endl
using namespace std;
typedef long long LL;

struct edge {
int to, cap, cost, rev;
};

int V;
vector<edge> G[MAXN];
int dist[MAXN];
int prevv[MAXN], preve[MAXN];

void add_edge(int from, int to, int cap, int cost)
{
G[from].push_back({ to, cap, cost, G[to].size() });
G[to].push_back({ from, 0, -cost, G[from].size() - 1 });
}

//求解从s到t流量为f的最小费用流
//不能增广返回-1
int min_cost_flow(int s, int t, int f)
{
int res = 0;
while (f > 0) {
fill(dist, dist + V, INF);
dist[s] = 0;
bool update = true;
while (update) {
update = false;
for (int v = 0; v < V; ++v) {
if (dist[v] == INF) continue;
for (int i = 0; i < G[v].size(); ++i) {
edge &e = G[v][i];
if (e.cap > 0 && dist[e.to] > dist[v] + e.cost) {
dist[e.to] = dist[v] + e.cost;
prevv[e.to] = v;
preve[e.to] = i;
update = true;
}
}
}
}

if (dist[t] == INF) return -1;

int d = f;
for (int v = t; v != s; v = prevv[v]) {
d = min(d, G[prevv[v]][preve[v]].cap);
}
f -= d;
res += d*dist[t];
for (int v = t; v != s; v = prevv[v]) {
edge &e = G[prevv[v]][preve[v]];
e.cap -= d;
G[v][e.rev].cap += d;
}
}
return res;
}

void solve()
{
int x, y, w, m;
cin >> V >> m;
int s = 0, t = V - 1;
for (int i = 0; i < m; ++i) {
cin >> x >> y >> w;
x--, y--;
add_edge(x, y, 1, w);
add_edge(y, x, 1, w);
}
cout << min_cost_flow(s, t, 2) << endl;
}

int main()
{
//freopen("data.in","r",stdin);
//freopen("data.out","w",stdout);
cin.tie(0);
ios::sync_with_stdio(false);
solve();
return 0;
}


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