1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
| #include <bits/stdc++.h> using namespace std;
template <class T> bool read(T &r) { r = 0; int ch = getchar(), f = 0; while (!isdigit(ch)) { if (ch == EOF) return true; f ^= (ch == '-'), ch = getchar(); } while (isdigit(ch)) (r *= 10) += ch - 48, ch = getchar(); if (f) r = -r; return false; } template <class T, class ...Ts> bool read(T &r, Ts &...rs) { return read(r) || read(rs...); }
const int maxn(5e3 + 5), maxm(1e5 + 5); const long long inf(0x3f3f3f3f3f3f3f3f);
int n, m, s, t; struct Edge { int v, nxt; long long c, w; } e[maxm]; int head[maxn], cur[maxn], cnt = 1; long long dis[maxn], ans, cost; bool vis[maxn];
void add(int u, int v, long long w, long long c) { e[++cnt].nxt = head[u]; head[u] = cnt; e[cnt].v = v, e[cnt].w = w, e[cnt].c = c; }
bool spfa() { deque<int> q; q.emplace_back(t); memset(vis, 0, sizeof vis); vis[t] = true; memset(dis, 0x3f, sizeof dis); dis[t] = 0; while (!q.empty()) { int u = q.front(); q.pop_front(); vis[u] = false; for (int i = head[u]; i; i = e[i].nxt) { if (e[i ^ 1].w && dis[e[i].v] > dis[u] - e[i].c) { dis[e[i].v] = dis[u] - e[i].c; if (!vis[e[i].v]) { vis[e[i].v] = true; if (!q.empty() && dis[e[i].v] < dis[q.front()]) q.emplace_front(e[i].v); else q.emplace_back(e[i].v); } } } } return dis[s] != inf; } long long dfs(int u = s, long long flow = inf) { vis[u] = true; if (!flow || u == t) return flow; long long rest = flow; for (int i = cur[u]; i; i = e[i].nxt) { cur[u] = i; if (!vis[e[i].v] && e[i].w && dis[e[i].v] == dis[u] - e[i].c) { long long f = dfs(e[i].v, min(e[i].w, rest)); e[i].w -= f, e[i ^ 1].w += f, rest -= f; if (!rest) break; } } return flow - rest; } void mcmf() { while (spfa()) do { memset(vis, 0, sizeof vis); memcpy(cur, head, sizeof cur); long long f = dfs(); ans += f, cost += dis[s] * f; } while (vis[t]); }
int main() { read(n, m, s, t); for (int i = 1; i <= m; i++) { int u, v; long long w, c; read(u, v, w, c); add(u, v, w, c); add(v, u, 0, -c); } mcmf(); printf("%lld %lld\n", ans, cost); return 0; }
|