Dinic
//#include<bits/stdc++.h>
#include<iostream>
#include<memory.h>
#include<queue>
using namespace std;
int const inf = 0x3f3f3f3f;
int const MAX = 205;
int n,m;
int c[MAX][MAX],dep[MAX];//流量,访问
int bfs(int start,int end)//建图
{
queue<int>q;
while(!q.empty())
q.pop();
memset(dep,-1,sizeof(dep));
dep[start]=0;
q.push(start);
while(!q.empty())
{
int now=q.front();
q.pop();
for(int i=0;i<=m;i++)
{
if(c[now][i]>0&&dep[i]==-1)//路通且没走过
{
dep[i]=dep[now]+1;
q.push(i);
}
}
}
return dep[end]!=-1;//找到了一条路
}
int dfs(int from,int flow,int to)//从from到to的最小流量
{
if(from==to)
return flow;
int temp;
for(int i=1;i<=m;i++)
{
if(c[from][i]>0&&dep[i]==dep[from]+1&&(temp=dfs(i,min(c[from][i],flow),to)))
{
c[from][i]-=temp;
c[i][from]+=temp;
return temp;
}
}
return 0;
}
int dinic()
{
int ans=0,temp;
while(bfs(1,m))
{
while(1)
{
temp = dfs(1,inf,m);
if(temp==0)//没有剩余的路了
break;
ans+=temp;
}
}
return ans;
}
int main()
{
while(~scanf("%d %d",&n,&m))
{
memset(c,0,sizeof(c));
int from,to,flow;
while(n--)
{
scanf("%d%d%d",&from,&to,&flow);
c[from][to]+=flow;//有可能不止一条边!!!
}
printf("%d\n",dinic());
}
return 0;
}
Edmonds Karp
#include <iostream>
#include <queue>
using namespace std;
const int N = 210;
const int INF = 0x7FFFFFFF;
int n,m,map[N][N],path[N],flow[N],start,end;
queue<int> q;
int bfs(){
int i,t;
while(!q.empty()) q.pop();
memset(path,-1,sizeof(path));
path[start]=0,flow[start]=INF;
q.push(start);
while(!q.empty()){
t=q.front();
q.pop();
if(t==end) break;
for(i=1;i<=m;i++){
if(i!=start && path[i]==-1 && map[t][i]){
flow[i]=flow[t]<map[t][i]?flow[t]:map[t][i];
q.push(i);
path[i]=t;
}
}
}
if(path[end]==-1) return -1;
return flow[m]; //一次遍历之后的流量增量
}
int Edmonds_Karp(){
int max_flow=0,step,now,pre;
while((step=bfs())!=-1){ //找不到增路径时退出
max_flow+=step;
now=end;
while(now!=start){
pre=path[now];
map[pre][now]-=step; //更新正向边的实际容量
map[now][pre]+=step; //添加反向边
now=pre;
}
}
return max_flow;
}
int main(){
int i,u,v,cost;
while(scanf("%d %d",&n,&m)!=EOF){
memset(map,0,sizeof(map));
for(i=0;i<n;i++){
scanf("%d %d %d",&u,&v,&cost);
map[u][v]+=cost; //not just only one input
} start=1,end=m;
printf("%d\n",Edmonds_Karp());
}
return 0;
}