Dinic算法的基本实现
#include <iostream>
#include <algorithm>
#include <queue>
#include <stack>
#include <cstdio>
#include <string>
#include <cstring>
#include <vector>
#include <set>
#include <cmath>
#define LL long long
#define INF 0x3f3f3f3f
#define mod 1000000007
const int maxn = 100 + 5;
using namespace std;
int edge[250][250];//邻接矩阵
int dis[250];//距源点距离,分层图
int n,m;//n点数,M边数
int bfs(int s, int e){//起点到终点
queue<int> q;
memset(dis, -1, sizeof(dis));
dis[s] = 0;
q.push(s);
while(!q.empty()){
int u = q.front(); q.pop();
for(int i=1; i<=n; i++){
if(dis[i] < 0 && edge[u][i] > 0){
dis[i] = dis[u] + 1;
q.push(i);
}
}
}
if(dis[e] > 0) return 1;
return 0;
}
int dfs(int s, int e, int low){
int a = 0;
if(s == e) return low;
for(int i=1; i<=n; i++){
if(edge[s][i] > 0 && dis[i] == dis[s] + 1 && (a = dfs(i,e,min(low,edge[s][i])))){
//联通, 是分层图的下一层, 能达到汇点
edge[s][i] -= a;
edge[i][s] += a;
return a;
}
}
return 0;
}
int main(){
while(scanf("%d%d",&m,&n) == 2){
memset(edge,0,sizeof(edge));
for(int i=1; i<=m; i++){
int f,t,flow;
scanf("%d%d%d",&f,&t,&flow);
edge[f][t] += flow;
}
int ans = 0;
int sum = 0;
while(bfs(1,n)){
while((sum = dfs(1,n,INF))) ans += sum;
}
printf("%d\n",ans);
}
return 0;
}