题目链接:
http://poj.org/problem?id=1273
题解:
网络流模板
代码:
EK算法:
#include <cmath>
#include <vector>
#include <queue>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#define inf 0x3f3f3f3f
#define met(a,b) memset(a,b,sizeof(a))
const int maxn = 200+10;
int mp[maxn][maxn];
bool visited[maxn];
int pre[maxn];
int n,m;
int bfs(int s,int t)
{
met(visited,0);
met(pre,0);
pre[s]=s;
visited[s]=true;
queue<int>q;
while(!q.empty())
q.pop();
q.push(s);
while(!q.empty())
{
int p=q.front();
q.pop();
for(int i=1;i<=m;i++)
{
if(mp[p][i]&&!visited[i])
{
visited[i]=1;
pre[i]=p;
if(i==t)
return true;
q.push(i);
}
}
}
return false;
}
int EX(int s,int t)
{
int ans=0,flow;
while(bfs(s,t))
{
flow=inf;
for(int i=t;i!=s;i=pre[i])
flow=min(flow,mp[pre[i]][i]);
for(int i=t;i!=s;i=pre[i])
{
mp[pre[i]][i]-=flow;
mp[i][pre[i]]+=flow;
}
ans+=flow;
}
return ans;
}
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
met(mp,0);
for(int i=0;i<n;i++)
{
int x,y,z;
scanf("%d%d%d",&x,&y,&z);
mp[x][y]+=z;
}
printf("%d\n",EX(1,m));
}
}
Dinic算法:
#include <cmath>
#include <vector>
#include <queue>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#define inf 0x7fffffff
#define met(a,b) memset(a,b,sizeof(a))
const int maxn = 200+100;
int mp[maxn][maxn];
int dis[maxn];
int s,t;
int n,m;
int bfs()
{
met(dis,0);
queue<int>q;
while(!q.empty())
q.pop();
dis[s]=1;
q.push(s);
while(!q.empty())
{
int p=q.front();
q.pop();
for(int i=1;i<=m;i++)
{
if(mp[p][i]&&!dis[i])
{
dis[i]=dis[p]+1;
q.push(i);
}
}
}
return dis[t]==0;
}
int dfs(int pos,int flow)
{
if(pos==t)
return flow;
int temp=flow;
for(int i=1;i<=m&&temp;i++)
{
if(mp[pos][i]&&(dis[i]==dis[pos]+1))
{
int a=dfs(i,min(mp[pos][i],temp));
mp[pos][i]-=a;
mp[i][pos]+=a;
temp-=a;
}
}
return flow-temp;
}
int Dinic()
{
int ans=0,temp=0;
while(!bfs())
{
while(temp=dfs(1,inf))
ans+=temp;
}
return ans;
}
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
met(mp,0);
for(int i=0;i<n;i++)
{
int x,y,z;
scanf("%d%d%d",&x,&y,&z);
mp[x][y]+=z;
}
s=1,t=m;
printf("%d\n",Dinic());
}
}

本文详细介绍了网络流中的两种经典算法——EK算法与Dinic算法。通过具体的代码实现展示了如何求解最大流问题,并提供了完整的C++实现代码。适用于对网络流算法感兴趣的读者。
608

被折叠的 条评论
为什么被折叠?



