H-Minimum-cost Flow

设 cost(u/v, 1) 表示容量为u/v,流量为1的总花费。

我们可以把网络扩大v/u倍,之后 cost(u/v,1) * (v/u) = cost(1, v/u)。

这样所有的边的容量都是1,我们可以跑mcmf,记录每一条增广路的价值。因为容量是1,因此每有一条增广路,总流量会加一。

因为每条增广路的价值是不减的,因此我们一定是顺序取,直到流量等于v/u。

别忘了最后乘以u/v,把网络缩小到原来的样子。

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int INF = 0x3f3f3f;
const int maxn = 105;
vector<ll> val;
ll sum[maxn];

struct Edge {
  int from, to, cap, flow, cost;
  Edge(int u, int v, int c, int f, int w)
      : from(u), to(v), cap(c), flow(f), cost(w) {}
};

struct MCMF {
  int n, m;
  vector<Edge> edges;
  vector<int> G[maxn];
  int inq[maxn];  //是否在队列中
  int d[maxn];    // bellmanford 到源点距离
  int p[maxn];    //上一条弧
  int a[maxn];    //可改进量

  void init(int n) {
    this->n = n;
    for (int i = 0; i <= n; i++) G[i].clear();
    edges.clear();
  }

  void AddEdge(int from, int to, int cap, int cost) {
    edges.push_back(Edge(from, to, cap, 0, cost));
    edges.push_back(Edge(to, from, 0, 0, -cost));
    m = edges.size();
    G[from].push_back(m - 2);
    G[to].push_back(m - 1);
  }

  bool BellmanFord(int s, int t, int& flow, ll& cost) {
    for (int i = 0; i <= n; i++) d[i] = INF;
    for (int i = 0; i <= n; i++) inq[i] = 0;
    d[s] = 0;
    inq[s] = 1;
    p[s] = 0;
    a[s] = INF;
    queue<int> Q;
    Q.push(s);
    while (!Q.empty()) {
      int u = Q.front();
      Q.pop();
      inq[u] = 0;
      for (int i = 0; i < G[u].size(); i++) {
        Edge& e = edges[G[u][i]];
        if (e.cap > e.flow && d[e.to] > d[u] + e.cost) {
          d[e.to] = d[u] + e.cost;
          p[e.to] = G[u][i];
          a[e.to] = min(a[u], e.cap - e.flow);
          if (!inq[e.to]) {
            Q.push(e.to);
            inq[e.to] = 1;
          }
        }
      }
    }
    if (d[t] == INF) return false;  // 当没有可增广的路时退出
    flow += a[t];
    cost += (ll)d[t] * (ll)a[t];
    val.push_back((ll)d[t] * (ll)a[t]);
    for (int u = t; u != s; u = edges[p[u]].from) {
      edges[p[u]].flow += a[t];
      edges[p[u] ^ 1].flow -= a[t];
    }
    return true;
  }

  int MincostMaxflow(int s, int t, ll& cost) {
    int flow = 0;
    cost = 0;
    while (BellmanFord(s, t, flow, cost))
      ;
    return flow;
  }
} mcmf;

int main() {
  int n, m, q;
  while (~scanf("%d%d", &n, &m)) {
    mcmf.init(n);
    val.clear();
    for (int i = 0, u, v, w; i < m; i++) {
      scanf("%d%d%d", &u, &v, &w);
      mcmf.AddEdge(u, v, 1, w);
    }
    ll uesless;
    mcmf.MincostMaxflow(1, n, uesless);
    for (int i = 1; i <= val.size(); i++) sum[i] = sum[i - 1] + val[i - 1];

    scanf("%d", &q);
    for (int i = 0, u, v; i < q; i++) {
      scanf("%d%d", &u, &v);
      if (!u || (v + u - 1) / u > val.size()) {
        puts("NaN");
        continue;
      }
      int x = v / u, y = v % u;
      ll num = sum[x] * u + val[x] * y, den = v;
      ll d = __gcd(num, den);
      printf("%lld/%lld\n", num / d, den / d);
    }
  }
}
最后修改:2020 年 08 月 05 日 01 : 48 PM