..突然发现自己拖了很久都没有学习有关网络流的东西了,所以先从模板开始写起吧.
dinic
code:
#include<iostream> #include<cstring> #include<queue> #define INF 0x3f3f3f3f const int MAXN = 1e6+5; struct side{ int from,to,next,w; }edge[MAXN]; int head[MAXN],depth[MAXN],n,m,s,t,len=-1; using namespace std; void ins(int x,int y,int d) { //利用结构体的赋值 edge[++len]= (side){x,y,head[x],d}; head[x]=len; } int bfs() { queue<int>q; fill(depth,depth+1+n,0); depth[s]=1;q.push(s); while(q.size()) { int now=q.front(); q.pop(); for(int k=head[now];k!=-1;k=edge[k].next){ //下一层未被访问 if(edge[k].w>0&&depth[edge[k].to]==0){ depth[edge[k].to]=depth[now]+1; q.push(edge[k].to); } } } //在未更新到汇点之前 return depth[t]!=0; } int dfs(int now,int flow) { //汇点停止 if(now==t) return flow; for(int k=head[now];k!=-1;k=edge[k].next) //流量大于0,切不是往回流 if(edge[k].w>0&&depth[edge[k].to]==depth[now]+1) { int minflow=dfs(edge[k].to,min(flow,edge[k].w)); if(minflow>0) { edge[k].w-=minflow; edge[k^1].w+=minflow; return minflow; } } return 0; } int dinic(int ans=0) { //在bfs广搜下进行深搜 while(bfs()) while(int flow=dfs(s,INF)) ans+=flow; return ans; } int main() { cin>>n>>m>>s>>t; fill(head,head+1+n,-1); for(int x,y,d,i=1;i<=m;i++){ cin>>x>>y>>d; ins(x,y,d);//正向建边 ins(y,x,0);//反向建边 } cout<<dinic(); }