社区讨论

不知道为什么超时求助

P3381【模板】最小费用最大流参与者 1已保存回复 1

讨论操作

快速查看讨论及其快照的属性,并进行相关操作。

当前回复
1 条
当前快照
1 份
快照标识符
@mhj3yg5q
此快照首次捕获于
2025/11/03 20:20
4 个月前
此快照最后确认于
2025/11/03 20:20
4 个月前
查看原帖
CPP
#include <bits/stdc++.h>
using namespace std;
struct root {
  int v;
  int c;
  int id;
};
long long C[500001], d[500001], ac[500001], ct = 0, cnt[500001], vis[500001];
int S[500001];
map<pair<int, int>, int> ma;

vector<root> g[200001];
long long ans1 = 0, ans2 = 0;
void adde(int u, int v, int s, int c) {
  if (ma.find({u, v}) == ma.end()) ma[{u, v}] = ct++;

  int now = ma[{u, v}];
  g[u].push_back({v, c, now});
  S[now] += s;
  C[now] = c;
}
int n, m, s, t;
bool spfa() {
  for (int i = 1; i <= n; i++) d[i] = 1e10, ac[i] = 0, cnt[i] = 0, vis[i] = 0;
  d[s] = 0;
  ac[s] = 1;
  queue<int> q;
  q.push(s);
  while (q.size()) {
    int now = q.front();
    q.pop();
    ac[now] = 0;
    for (root nx : g[now]) {
      if (S[nx.id] && d[nx.v] > d[now] + nx.c) {
        d[nx.v] = d[now] + nx.c;
        if (!ac[nx.v]) {
          ac[nx.v] = 1;
          q.push(nx.v);
        }
      }
    }
  }
  return d[t] <= 1e9;
}
int dfs(int now, int flow) {
  if (now == t) return flow;
  int nowflow = 0;
  vis[now] = 1;
  for (int i = cnt[now]; i < g[now].size(); i++) {
    root nx = g[now][i];
    cnt[now] = i;
    if (S[nx.id] && !vis[nx.v] && d[nx.v] == d[now] + nx.c) {
      int ds = dfs(nx.v, min(flow - nowflow, S[nx.id]));

      if (ds > 0) {
        nowflow += ds;
        S[nx.id] -= ds;
        S[nx.id ^ 1] += ds;
        if (nowflow == flow) break;
      }
    }
  }
  vis[now] = 0;
  return nowflow;
}
int main() {
  cin >> n >> m >> s >> t;
  for (int i = 1; i <= m; i++) {
    int u, v, w, c;
    cin >> u >> v >> w >> c;
    adde(u, v, w, c);
    adde(v, u, 0, -c);
  }

  while (spfa()) {
    while (int de = dfs(s, INT_MAX / 2)) {
      ans1 += de;
      ans2 += de * d[t];
    }
  }
  cout << ans1 << " " << ans2;
}

回复

1 条回复,欢迎继续交流。

正在加载回复...