2 3 2 1 2 1 2 3 1 3 3 1 2 1 2 3 1 1 3 1
Case 1: 1 Case 2: 2
初学网络流。。
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <queue> #include <iostream> #include <algorithm> using namespace std; const int inf = 1e8; int cap[50][50],flow[50][50],a[50],pre[50]; //cap 容量 flow 流量 a标记&&最小 pre 记录前驱 int t,n,m,x,y,c,maxflow,cas; void bfs ()//找增广路 { queue <int >q; memset (flow,0,sizeof (flow)); while (1) { memset (a,0,sizeof (a)); pre[1] = -1; a[1] = inf; q.push (1); while (!q.empty()) { int u = q.front(); q.pop (); for (int v = 1; v <= n; v++) { if ( !a[v] && cap[u][v] > flow[u][v]) { q.push (v); pre[v] = u; a[v] = min (a[u],cap[u][v] - flow[u][v]);//1-->v的最小残量 } } } if ( a[n] == 0)//找不到 目前已是最大流 break; maxflow += a[n]; for (int v = n; v != -1 ; v = pre[v]) { flow[pre[v]][v] += a[n];///正向加 flow[v][pre[v]] -= a[n];///反向减 为了给程序一个后悔的机会 因为BFS 找的可能不是当前最小 } } printf ("Case %d: %d\n",cas++,maxflow); } int main() { scanf ("%d",&t); cas = 1; while ( t-- ) { maxflow = 0; scanf ("%d%d",&n,&m); memset (cap,0,sizeof (cap)); for (int i = 0 ; i < m; i++) { scanf ("%d%d%d",&x,&y,&c); cap[x][y] += c; } bfs (); } return 0; }