hdu1532(网络流模板)

#include<bits/stdc++.h>
using namespace std;
const int inf=0x3f3f3f3f;
const int maxn=205;
int n,m,g[maxn][maxn],pre[maxn],flow[maxn];
bool bfs(int s,int t,int v){
	memset(pre,-1,sizeof(pre));
	memset(flow,inf,sizeof(flow));
	queue<int >q;
	q.push(s);
	pre[s]=0;//pre[s]==0表示s已经走过,下次不用看,避免重复算。
	while(!q.empty()){
		int now=q.front();
		if(now==t) break;
		for(int i=1;i<=v;i++)
			//pre[]==-1未走过,g[][]>0说明正向有路
            if(pre[i]==-1&&g[now][i]>0){
				pre[i]=now;
                flow[i]=min(flow[now],g[now][i]);
                q.push(i);
            }
		q.pop();
	}
	return pre[t]!=-1;
	//pre[t]==-1表示t没有前驱结点即找不到增广路
}
void update(int s,int t){
	for(int fa,now=t;now!=s;now=fa)
		fa=pre[now],g[fa][now]-=flow[t],g[now][fa]+=flow[t]; 
		//flow[t]记录这条路上最小的流量,所以整条路都用t
}
int main(){
	int u,v,w,maxf;
	while(~scanf("%d%d",&n,&m)){
		memset(g,0,sizeof(g));
		maxf=0;
		for(int i=1;i<=n;i++)
			scanf("%d%d%d",&u,&v,&w),g[u][v]+=w;
		while(bfs(1,m,m)) //起点,终点,最终要到达的点
			maxf+=flow[m],update(1,m);
		printf("%d\n",maxf);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_50904510/article/details/120267519
今日推荐