lingo求最小费用最大流问题的代码
时间: 2023-08-04 16:08:37 浏览: 56
以下是一个基于Dijkstra算法的最小费用最大流实现代码:
```cpp
#include <iostream>
#include <queue>
#include <cstring>
#include <cstdio>
#include <algorithm>
using namespace std;
const int INF = 0x7fffffff;
const int MAXN = 1005;
const int MAXM = 10005;
int n, m, s, t, ans_flow, ans_cost, head[MAXN], h[MAXN], pre[MAXN];
bool vis[MAXN];
struct Edge{
int to, nxt, flow, cost;
}edge[MAXM << 1];
void addEdge(int from, int to, int flow, int cost){
edge[m].to = to;
edge[m].flow = flow;
edge[m].cost = cost;
edge[m].nxt = head[from];
head[from] = m++;
edge[m].to = from;
edge[m].flow = 0;
edge[m].cost = -cost;
edge[m].nxt = head[to];
head[to] = m++;
}
bool spfa(){
queue<int> q;
memset(h, 0x3f, sizeof(h));
memset(vis, false, sizeof(vis));
memset(pre, -1, sizeof(pre));
h[s] = 0;
q.push(s);
while(!q.empty()){
int u = q.front();
q.pop();
vis[u] = false;
for(int i = head[u]; ~i; i = edge[i].nxt){
int v = edge[i].to;
if(edge[i].flow && h[v] > h[u] + edge[i].cost){
h[v] = h[u] + edge[i].cost;
pre[v] = i;
if(!vis[v]){
vis[v] = true;
q.push(v);
}
}
}
}
return pre[t] != -1;
}
void MCMF(){
while(spfa()){
int min_flow = INF;
for(int i = pre[t]; ~i; i = pre[edge[i ^ 1].to]){
min_flow = min(min_flow, edge[i].flow);
}
ans_flow += min_flow;
ans_cost += min_flow * h[t];
for(int i = pre[t]; ~i; i = pre[edge[i ^ 1].to]){
edge[i].flow -= min_flow;
edge[i ^ 1].flow += min_flow;
}
}
}
int main(){
memset(head, -1, sizeof(head));
scanf("%d%d%d%d", &n, &m, &s, &t);
for(int i = 1; i <= m; i++){
int u, v, f, c;
scanf("%d%d%d%d", &u, &v, &f, &c);
addEdge(u, v, f, c);
}
MCMF();
printf("%d %d\n", ans_flow, ans_cost);
return 0;
}
```
该代码实现了最小费用最大流,其中s和t分别代表源点和汇点。通过添加addEdge函数,将边加入邻接表中,然后通过MCMF函数调用Dijkstra算法求解最小费用最大流。最后输出最大流和最小费用即可。