取自https://www.cnblogs.com/pk28/p/8039645.html
基本不考虑ek了
#include<bits/stdc++.h> using namespace std; const int N=205; const int inf=0x7fffffff; int mp[N][N]; //残留网络,初始化为原图 bool visit[N]; int pre[N]; int m,n; bool bfs(int s,int t) //寻找一条从s到t的增广路,若找到返回true { int p; queue<int > q; memset(pre,-1,sizeof(pre)); memset(visit,false,sizeof(visit)); pre[s]=s; visit[s]=true; q.push(s); while(!q.empty()) { p=q.front(); q.pop(); for(int i=1;i<=n;i++) { if(mp[p][i]>0&&!visit[i]) { pre[i]=p; visit[i]=true; if(i==t) return true; q.push(i); } } } return false; } int EdmondsKarp(int s,int t) { int flow=0,d,i; while(bfs(s,t)) { d=inf; for(i=t;i!=s;i=pre[i]) d=d<mp[pre[i]][i]? d:mp[pre[i]][i]; for(i=t;i!=s;i=pre[i]) { mp[pre[i]][i]-=d; mp[i][pre[i]]+=d; } flow+=d; } return flow; } int main() { while(scanf("%d%d",&m,&n)!=EOF)//m条路 n个点 1是原点 n是汇点 { int u,v,w; memset(mp,0,sizeof(mp)); for(int i=0;i<m;i++) { scanf("%d%d%d",&u,&v,&w); mp[u][v]+=w; } printf("%d ",EdmondsKarp(1,n)); } return 0; }
dinic
#include<cstring> #include<cstdio> #include<vector> #include<queue> #include<iostream> using namespace std; typedef long long ll; const int INF = 0x3f3f3f3f; const int N = 2000 ; int p[N],s[N],e[N],v,c,k; struct Edge { int from, to, cap, flow; }; bool operator < (const Edge& a, const Edge& b) { return a.from < b.from || (a.from == b.from && a.to < b.to); } struct Dinic { int s,t; vector<Edge> edges; // 边数的两倍 vector<int> G[N]; // 邻接表,G[i][j]表示结点i的第j条边在e数组中的序号 bool vis[N]; // BFS使用 int d[N]; // 从起点到i的距离 int cur[N]; // 当前弧指针 void init(int n) { for(int i = 0; i <= n; i++) G[i].clear(); edges.clear(); } void AddEdge(int from, int to, int cap) { edges.push_back((Edge){from, to, cap, 0}); edges.push_back((Edge){to, from, 0, 0}); k = edges.size(); G[from].push_back(k-2); G[to].push_back(k-1); } bool BFS() { memset(vis, 0, sizeof(vis)); queue<int> Q; Q.push(s); vis[s] = 1; d[s] = 0; while(!Q.empty()) { int x = Q.front(); Q.pop(); for(int i = 0; i < G[x].size(); i++) { Edge& e = edges[G[x][i]]; if(!vis[e.to] && e.cap > e.flow) { vis[e.to] = 1; d[e.to] = d[x] + 1; Q.push(e.to); } } } return vis[t]; } int DFS(int x, int a) { if(x == t || a == 0) return a; int flow = 0, f; for(int& i = cur[x]; i < G[x].size(); i++) { Edge& e = edges[G[x][i]]; if(d[x] + 1 == d[e.to] && (f = DFS(e.to, min(a, e.cap-e.flow))) > 0) { e.flow += f; edges[G[x][i]^1].flow -= f; flow += f; a -= f; if(a == 0) break; } } return flow; } int Maxflow(int s, int t) { this->s = s; this->t = t; int flow = 0; while(BFS()) { memset(cur, 0, sizeof(cur)); flow += DFS(s, INF); } return flow; } }g; int main() { int n,m; g.init(N);//一定要初始化!!!! }