题目描述:给予一张图,源点 1,汇点 n 求最大流。
标准模板题,附上封装好的Dinic模板。
#include <algorithm> #include <iostream> #include <cstring> #include <queue> #include <map> #include <set> using namespace std; #define N 5005 #define inf 0x3f3f3f3f typedef long long ll; class graphic{ public: void init(){ memset(head,-1, sizeof(head)); cnt = 0; } void add(int u,int v,int d){ _add(u,v,d); _add(v,u,0); } long long Dinic(){ long long ans = 0; while (bfs()){ ans+=dfs(st,0x3f3f3f3f); } return ans; } void setST(int a,int b){///设置源汇点 st = a,en = b; } private: struct E{ int to,next,val; }edge[N]; int head[20],cnt,dep[20]; bool dfsVis[20]; int st,en; void _add(int u,int v,int d){ edge[cnt].val = d; edge[cnt].to = v; edge[cnt].next = head[u]; head[u] = cnt++; } bool bfs(){ memset(dfsVis, false, sizeof(dfsVis)); memset(dep,-1, sizeof(dep)); queue<int>qq; qq.push(st); dep[st] = 0; while (!qq.empty()){ int u = qq.front(); qq.pop(); for(int i = head[u],v ; ~i ; i = edge[i].next){ v = edge[i].to; if(edge[i].val and -1==dep[v] ){ dep[v] = dep[u]+1; qq.push(v); } } } return dep[en]!=-1; } int dfs(int u,int f){ if(u==en){ return f; } dfsVis[u] = true; int a; for(int i = head[u],v;~i ; i = edge[i].next){ v = edge[i].to; if(edge[i].val and !dfsVis[v] and dep[v] == dep[u]+1 and (a = dfs(v,min(f,edge[i].val)))){ edge[i].val-=a; edge[i^1].val+=a; return a; } } return 0; } }; graphic ss; int main(){ int t,n,m,u,v,d; cin>>t; for(int i = 1 ; i <= t ; ++i){ ss.init(); cin>>n>>m; printf("Case %d: ",i); while (m--){ scanf("%d%d%d",&u,&v,&d); ss.add(u,v,d); } ss.setST(1,n); printf("%lld ",ss.Dinic()); } }