网络流 EK算法
#include <iostream> #include <queue> #include <algorithm> #include <cstdio> #include <cstring> #define maxn 205 using namespace std; const int inf=1e9; int mp[maxn][maxn]={0}; int pre[maxn]={0}; bool vis[maxn]={0}; int n; bool bfs(int s,int t) { queue<int> q; memset(vis,false,sizeof(vis)); memset(pre,-1,sizeof(pre)); vis[s]=true; pre[s]=s; q.push(s); while(!q.empty()) { int now=q.front(); q.pop() for(int i=1;i<=n;i++) { if(mp[now][i]&&!vis[i]) { vis[i]=true; pre[i]=now; if(i==t) return true; q.push(i); } } } return false; } int ek(int s,int t) { int ans=0,i; while(bfs(s,t)) { int minum=inf; for(i=t;i!=s;i=pre[i]) { minum=min(minum,mp[pre[i]][i]); } for(i=t;i!=s;i=pre[i]) { mp[pre[i]][i]-=minum; mp[i][pre[i]]+=minum; } ans+=minum; } return ans; } int main() { int t; while(~scanf("%d%d",&t,&n)) { memset(mp,0,sizeof(mp)); while(t--) { int x,y,z; cin>>x>>y>>z; mp[x][y]+=z; } cout<<ek(1,n)<<endl;} return 0; }
2.邻接表实现
#include <iostream> #include <cstring> #include <algorithm> #include <queue> #define maxn 2005 using namespace std; typedef long long ll; struct edge { int u; int v; int w; int next; }edge[maxn]; struct node { int v,id; }; int cnt=0; int head[maxn]; void addedge(int u,int v,int w) { edge[cnt].u=u; edge[cnt].v=v; edge[cnt].w=w; edge[cnt].next=head[u]; head[u]=cnt++; } node pre[maxn]; bool vis[maxn]={0}; bool bfs(int s,int t) { memset(vis,false,(sizeof(vis))); memset(pre,-1,sizeof(pre)); queue<int> q; q.push(s); vis[s]=true; while(!q.empty()) { int u=q.front(); q.pop(); for(int i=head[u];i!=-1;i=edge[i].next) { int v=edge[i].v; if(!vis[v]&&edge[i].w) { pre[v].v=u; pre[v].id=i; vis[v]=true; if(v==t) return true; q.push(v); } } } return false; } int ek(int s,int t) { int ans=0,i; while(bfs(s,t)) { int minum=1e9; for(i=t;i!=s;i=pre[i].v) { minum=min(minum,edge[pre[i].id].w); } for(i=t;i!=s;i=pre[i].v) { edge[pre[i].id].w-=minum; edge[pre[i].id^1].w+=minum; } ans+=minum; } return ans; } int main() { int n,m,i; while(cin>>m>>n) { memset(head,-1,sizeof(head)); memset(edge,0,sizeof(edge)); for(i=1;i<=m;i++) { int u,v,w; cin>>u>>v>>w; addedge(u,v,w); addedge(v,u,0); } cout<<ek(1,n)<<endl; } return 0; }