MaxFlow(最大流增广路算法)

#include #include #include using namespace std; const int MAXN = 201; int cap[MAXN][MAXN]; //残留网络,初始为原图 int flow[MAXN][MAXN]; int vernum; //节点总数量 int pre[MAXN]; int BFS(const int &s, const int &t) { queueq; memset(pre,-1,sizeof(pre)); q.push(s); pre[s] = s; while (!q.empty()) { int u = q.front(); q.pop(); for (int v=0;v0) ) { pre[v] = u; q.push(v); if (v == t) return 1; } } } return 0; } void TrackBack(const int &s, const int &t) { int v,min = 0x7fffffff; int i=t; while (i != s) { v = pre[i]; if (flow[v][i] < cap[v][i]) { if(min > cap[v][i] - flow[v][i]) min = cap[v][i] - flow[v][i]; } else { if (flow[i][v] > 0) { if(min > flow[i][v]) min = flow[i][v]; } } i = v; } i = t; while (i != s) { v = pre[i]; if (flow[v][i] < cap[v][i])//前进流+min flow[v][i] += min; else { if (flow[i][v] > 0) flow[i][v] -= min; } i = v; } } int MaxFlow(const int &s, const int &t) { while (BFS(s, t)) TrackBack(s, t); int res = 0; for(int i=0;i> vernum >> arcnum) { memset(cap,0,sizeof(cap)); memset(flow,0,sizeof(flow)); while (arcnum--) { cin >> f >> t >> w; cap[f-1][t-1] += w; } int ans = MaxFlow(0,vernum-1); cout << ans << endl; } return 0; }

你可能感兴趣的:(MaxFlow(最大流增广路算法))