最小费用最大流的问题,注意在每次我们寻找的都是可以进行增广的条件下将总的费用尽可能地压缩,这也就保证了在流最大的前提下,尽可能地压缩费用的要求,具体实现见如下代码:
#include<iostream>
#include<vector>
#include<string>
#include<set>
#include<stack>
#include<queue>
#include<map>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<cstring>
#include<sstream>
#include<cstdio>
#include<deque>
#include<functional>
using namespace std;
class Edge{
public:
int from, to, cap, flow, cost;
};
class Solve{
public:
int n, m;
int start, end;
vector<Edge> edge;
vector<int> G[1005];
int price[1005];
bool inq[1005];
int parent[1005];
int Flow[1005];
const int Inf = 0x3f3f3f3f;
void Init(){
cin >> n >> m >> start >> end;
for (int i = 0; i < m; i++){
Edge temp;
cin >> temp.from >> temp.to >> temp.cap >> temp.cost;
temp.flow = 0;
Edge temp1;
temp1.from = temp.to, temp1.to = temp.from, temp1.cap = 0, temp1.from = 0, temp1.cost = -temp.cost;
edge.push_back(temp);
edge.push_back(temp1);
int t = edge.size();
G[temp.from].push_back(t - 2);
G[temp1.from].push_back(t - 1);
}
}
bool BellMan_Floyd(long long &flow, long long& cost){
memset(price, Inf, sizeof(price));
memset(inq, false, sizeof(inq));
Flow[1] = Inf;
price[start] = 0;
inq[start] = true;
queue<int> q;
q.push(start);
while (!q.empty()){
int id = q.front();
q.pop();
inq[id] = false;
for (int j = 0; j < G[id].size(); j++){
int ide = G[id][j];
int to = edge[ide].to;
if (edge[ide].cap > edge[ide].flow&&price[to] > price[id] + edge[ide].cost){
price[to] = price[id] + edge[ide].cost;
parent[to] = ide;
Flow[to] = min(Flow[id], edge[ide].cap - edge[ide].flow);
if (!inq[to]){
q.push(to);
inq[to] = true;
}
}
}
}
if (price[end] == Inf) return false;
flow += Flow[end];
cost += (long long)price[end] * (long long)Flow[end];
for (int i = end; i != start; i = edge[parent[i]].from){
edge[parent[i]].flow += Flow[end];
edge[parent[i] ^ 1].flow -= Flow[end];
}
return true;
}
void Deal(){
Init();
long long flow = 0;
long long cost = 0;
while (BellMan_Floyd(flow, cost));
cout << "flow: " << flow << endl;
cout << "cost: " << cost << endl;
}
};
int main(){
Solve a;
a.Deal();
system("pause");
return 0;
}
/*
4 5
1 3
1 2 2 2
2 3 1 3
2 4 1 2
1 4 1 5
4 3 1 1
*/