链接:点击跳转
网络流模板题
代码如下:
#include<bits/stdc++.h>
using namespace std;
typedef unsigned long long ll;
const int MAXN = 2e3 + 5;
const int INF = 0x3f3f3f3f;
#define endl '\n'
inline void IO_STREAM() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
}
struct Edge{
int to,val,nxt;
}e[MAXN];
int head[MAXN], deep[MAXN];
int n, m, s, t, cnt;
ll res;
inline void init() {
for (int i = 1; i <= n; i++) head[i] = -1;
cnt = 0;
}
inline void add(int from, int to, int val) {
e[cnt] = Edge{to, val, head[from]};
head[from] = cnt++;
}
inline int bfs() {
for (int i = 2; i <= t; i++) deep[i] = -1;
queue<int>q;
deep[s] = 1;
q.push(s);
while (!q.empty()) {
int front = q.front();
q.pop();
for (int i = head[front]; i != -1; i = e[i].nxt) {
if (deep[e[i].to] == -1 && e[i].val) {
deep[e[i].to] = deep[front] + 1;
q.push(e[i].to);
}
}
}
return (deep[t] != -1);
}
inline int dfs(int x, int totFlow) {
if (x == t || totFlow ==0) return totFlow;
int ans = totFlow;
for (int i = head[x]; i != -1; i = e[i].nxt) {
if (deep[e[i].to] == deep[x] + 1 && e[i].val) {
int flow = dfs(e[i].to, min(totFlow,e[i].val));
e[i].val -= flow;
e[i ^ 1].val += flow;
totFlow -= flow;
if (totFlow == 0) return ans;
}
}
return ans - totFlow;
}
inline void dinic() {
while (bfs()) {
res += dfs(s, INF);
}
}
int main() {
IO_STREAM();
int Case;
int ans = 1;
cin >> Case;
while (Case--) {
cin >> n >> m;
s = 1, t = n;
init();
for (int i = 0; i < m; i++) {
int x, y, c;
cin >> x >> y >> c;
add(x, y, c);
add(y, x, 0);//建反边
}
res = 0;
dinic();
cout << "Case " << ans++ << ": " << res << endl;
}
return 0;
}