hdu Flow Problem (最大流 裸题)
最大流裸题,贴下模版
view code#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <cmath> #include <vector> #include <queue> using namespace std; const int INF = 0x3f3f3f3f; const int maxn = 1000; int n, m, s, t, cas=1, _; int pre[maxn], d[maxn], cur[maxn]; bool vis[maxn]; struct Edge { int from, to, cap, flow, p; Edge() {} Edge(int from, int to, int cap, int flow, int pre):from(from), to(to), cap(cap), flow(flow), p(pre) {} }e[maxn*maxn]; int ecnt = 0; void init() { memset(pre, -1, sizeof(pre)); ecnt = 0; s = 1, t = n; } bool BFS() { memset(vis, 0, sizeof(vis)); queue<int > q; q.push(s); vis[s] = 1; d[s] = 0; while(!q.empty()) { int u = q.front(); q.pop(); for(int i = pre[u]; ~i; i=e[i].p) { int v = e[i].to; if(!vis[v] && e[i].flow<e[i].cap) { d[v] = d[u] + 1; vis[v] = true; q.push(v); } } } return vis[t]; } int DFS(int u, int c) { if(u==t || c==0) return c; int flow = 0, f; for(int &i=cur[u]; ~i; i=e[i].p) { int v = e[i].to; if(d[v]==d[u]+1 && (f=DFS(v, min(c, e[i].cap-e[i].flow)))>0) { e[i].flow += f; e[i^1].flow -= f; flow += f; c -= f; if(c==0) break; } } return flow; } int main() { // freopen("in.txt", "r", stdin); scanf("%d", &_); while(_--) { scanf("%d%d", &n, &m); init(); int u, v, w; for(int i=0; i<m; i++) { scanf("%d%d%d", &u, &v, &w); e[ecnt] = Edge(u, v, w, 0, pre[u]); pre[u] = ecnt++; e[ecnt] = Edge(v, u, 0, 0, pre[v]); pre[v] = ecnt++; } int ans = 0; while(BFS()) { for(int i=1; i<=n; i++) cur[i] = pre[i]; ans += DFS(s, INF); } printf("Case %d: %d\n", cas++, ans); } }