您的位置:首页 > 其它

POJ 2135 Farm Tour(最小费用最大流模板题)

2017-07-13 20:09 429 查看
http://poj.org/problem?id=2135

题意很简单,就是给出m条无向边,你要从1到n,然后从n回到1,要求走过的路不能再走,问这样走的最少时间是多少。

一开始我很愚蠢的用正反网络流来跑,这样是错误的。因为这样就没有退流了。

正解:设置一个超级源点0和一个超级汇点n+1,0到1的流量为2,花费为0,n+1到n的流量为2,花费为0.然后我们要求从0到n+1求最小费用,套板子即可。

而且可以注意到,因为一条边只能走一次,所以我们把每条边的流量都设置为1即可。

那么他是无向图,我们怎么增加边呢?

对于单纯的spfa,确实只需要正反两条边都设置一下即可。

但是这题每条边是有费用的,也就是通过这条路的时间。如果你走了这条边,你的费用会+cost。如果你走第二遍发现这条边不走更好,那么你就会退回这条边的流量,并且费用也会-cost。所以我们这题我们一条边需要开四条边才对。超级源点超级汇点除外,只需正反即可。

代码如下:

#include<iostream>
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
const int INF = 0x7fffffff;
const int maxn = 10000 + 5;
int n, m, ans = 0;
int head[maxn], to[maxn * 4], front[maxn * 4], flow[maxn * 4], cost[maxn * 4], ppp;
int dis[maxn], minflow[maxn];
bool flag[maxn];
pair<int, int> par[maxn];

bool spfa(int s, int e)
{
int u, v;
for(int i = 0; i <= n + 1; i++)
dis[i] = INF;
memset(flag, 0, sizeof(flag));
dis[s] = 0;
minflow[s] = INF;
queue <int> q;
q.push(s);
while(!q.empty())
{
u = q.front();
q.pop();
flag[u] = 0;
for(int i = head[u]; ~i; i = front[i])
{
v = to[i];
if(flow[i] && dis[v] > dis[u] + cost[i])
{
dis[v] = dis[u] + cost[i];
par[v] = (make_pair(u, i));
minflow[v] = min(minflow[u], flow[i]);
if(!flag[v])
{
flag[v] = 1;
q.push(v);
}
}
}
}
if(dis[e] == INF)
return 0;
return 1;
}

void Min_Cost_Max_Flow(int s, int e)
{
int p;
while(spfa(s, e))
{
p = e;
while(p != s) {
flow[par[p].second] -= minflow[e];
flow[par[p].second^1] += minflow[e];
p = par[p].first;
}
ans += dis[e];
}
cout << ans << endl;
}

void add(int u, int v, int f, int c)
{
to[ppp] = v;
front[ppp] = head[u];
flow[ppp] = f;
cost[ppp] = c;
head[u] = ppp++;
}

int main()
{
int u, v, c;
memset(head, -1, sizeof(head));
ppp = 0;
scanf("%d%d", &n, &m);
while(m--)
{
scanf("%d%d%d", &u, &v, &c);
add(u, v, 1, c);
add(v, u, 0, -c);
add(v, u, 1, c);
add(u, v, 0, -c);
}
add(0, 1, 2, 0);
add(1, 0, 0, 0);
add(n, n + 1, 2, 0);
add(n + 1, n, 0, 0);
Min_Cost_Max_Flow(0, n + 1);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: