题目链接:https://www.luogu.org/problem/show?pid=3376
Dinic求最大流
我的模板库
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<queue>
using namespace std;const int inf=(1<<30),N_SIZE=100010,M_SIZE=1000010;
struct edge
{int v,nxt,cap,flow;
}e[M_SIZE];
int n,m,s,t,ecnt,head[N_SIZE],level[N_SIZE];inline void add_edge(int u,int v,int w)
{e[ecnt].nxt=head[u];e[ecnt].v=v;e[ecnt].cap=w;head[u]=ecnt++;e[ecnt].nxt=head[v];e[ecnt].v=u;e[ecnt].cap=0;head[v]=ecnt++;
}inline bool BFS()
{memset(level,0,sizeof(level));level[s]=1;queue<int> q;q.push(s);while(!q.empty()){int u=q.front();q.pop();for(int i=head[u];i!=-1;i=e[i].nxt){int v=e[i].v;if(e[i].cap>0&&(!level[v])){level[v]=level[u]+1;q.push(v);}}}return level[t];
}inline int DFS(int u,int maxflow)
{if(!maxflow||u==t) return maxflow;int ret=0;for(int i=head[u];i!=-1;i=e[i].nxt){int v=e[i].v;if(e[i].cap>0&&level[v]==level[u]+1){int temp=DFS(v,min(maxflow,e[i].cap));ret+=temp;maxflow-=temp;e[i].cap-=temp;e[i^1].cap+=temp;}}return ret;
}int Dinic()
{int ret=0;while(BFS()) ret+=DFS(s,inf);return ret;
}int main()
{scanf("%d%d%d%d",&n,&m,&s,&t);memset(head,-1,sizeof(head));for(int i=1,x,y,z;i<=m;i++){scanf("%d%d%d",&x,&y,&z);add_edge(x,y,z);}printf("%d",Dinic());return 0;
}