這道題要注意一下幾個問題:
第一、所有的路都是雙向,也兩個方向上的流量相等
第二、剛開始寫模板的時候,寫錯了,但是原因我還沒有想得很清楚
總之代碼如下:
#include <cstdio>#include <cstring>#include <queue>#include <algorithm>using namespace std;const int N = 110;const int INF = 10000;int S, T, M, n, flow[N][N], cap[N][N];int p[N], a[N];int maxFlow () { queue <int> q; memset( flow, 0, sizeof(flow)); int f = 0; while ( 1 ) { memset( a, 0, sizeof(a)); a[S] = INF; q.push(S); while ( !q.empty() ) { int u = q.front(); q.pop(); //if ( u == T ) break;(開始的時候就把這個寫上了,但是wa了,去掉了就ac了 如果有朋友知道這是為什麼,請留言給我,感激不盡 for ( int v = 1; v <= n; ++v ) { if ( !a[v] && cap[u][v] > flow[u][v] ) { p[v] = u; a[v] = min( a[u], cap[u][v] - flow[u][v]); q.push(v); } } } if ( a[T] == 0 ) break; for ( int u = T; u != S; u = p[u] ) { flow[p[u]][u] += a[T]; flow[u][p[u]] -= a[T]; } f += a[T]; } return f;}int main(){ int icase = 0; while ( scanf("%d", &n), n ) { scanf("%d%d%d", &S, &T, &M); memset(cap, 0, sizeof(cap)); while ( M-- ) { int s, t, c; scanf("%d%d%d", &s, &t, &c); cap[s][t] += c; cap[t][s] = cap[s][t]; } printf("Network %d\n", ++icase); printf("The bandwidth is %d.\n\n", maxFlow()); }}