使用JAVA实现最小费用最大流,带上中文注释,包含主函数
时间: 2024-03-17 15:44:50 浏览: 222
以下是使用Java实现最小费用最大流的完整代码,包括了主函数和中文注释:
```java
import java.util.Arrays;
import java.util.LinkedList;
public class MinCostMaxFlow {
private int n, m, s, t, maxFlow, minCost;
private int[] head, dis, pre, flow, vis;
private Edge[] edges;
private LinkedList<Integer> queue;
public MinCostMaxFlow(int n, int m, int s, int t) {
this.n = n;
this.m = m;
this.s = s;
this.t = t;
this.head = new int[n + 1];
this.edges = new Edge[m + 1];
this.dis = new int[n + 1];
this.pre = new int[n + 1];
this.flow = new int[n + 1];
this.vis = new int[n + 1];
this.queue = new LinkedList<>();
Arrays.fill(head, -1);
}
public void addEdge(int u, int v, int cap, int cost) {
edges[m] = new Edge(u, v, cap, cost, head[u]);
head[u] = m++;
edges[m] = new Edge(v, u, 0, -cost, head[v]);
head[v] = m++;
}
private boolean spfa() {
Arrays.fill(dis, Integer.MAX_VALUE);
Arrays.fill(vis, 0);
dis[s] = 0;
vis[s] = 1;
flow[s] = Integer.MAX_VALUE;
queue.add(s);
while (!queue.isEmpty()) {
int u = queue.poll();
vis[u] = 0;
for (int i = head[u]; i != -1; i = edges[i].next) {
int v = edges[i].v;
if (edges[i].cap > 0 && dis[v] > dis[u] + edges[i].cost) {
dis[v] = dis[u] + edges[i].cost;
pre[v] = i;
flow[v] = Math.min(flow[u], edges[i].cap);
if (vis[v] == 0) {
vis[v] = 1;
queue.add(v);
}
}
}
}
return dis[t] != Integer.MAX_VALUE;
}
public void minCostMaxFlow() {
while (spfa()) {
int u = t;
maxFlow += flow[t];
minCost += dis[t] * flow[t];
while (u != s) {
edges[pre[u]].cap -= flow[t];
edges[pre[u] ^ 1].cap += flow[t];
u = edges[pre[u]].u;
}
}
}
static class Edge {
int u, v, cap, cost, next;
public Edge(int u, int v, int cap, int cost, int next) {
this.u = u;
this.v = v;
this.cap = cap;
this.cost = cost;
this.next = next;
}
}
public static void main(String[] args) {
int n = 4; // 点的数量
int m = 5; // 边的数量
int s = 1; // 源点
int t = 4; // 汇点
MinCostMaxFlow mcmf = new MinCostMaxFlow(n, m, s, t);
mcmf.addEdge(1, 2, 2, 2); // 添加边
mcmf.addEdge(1, 3, 1, 4);
mcmf.addEdge(2, 3, 1, 1);
mcmf.addEdge(2, 4, 1, 3);
mcmf.addEdge(3, 4, 2, 1);
mcmf.minCostMaxFlow(); // 求解最小费用最大流
System.out.println("最大流量: " + mcmf.maxFlow);
System.out.println("最小费用: " + mcmf.minCost);
}
}
```
在主函数中首先创建一个最小费用最大流的对象,然后添加边,最后调用`minCostMaxFlow`方法求解最小费用最大流。最大流量和最小费用分别保存在`maxFlow`和`minCost`变量中。
阅读全文