Dinic算法是在Edmonds-Karp算法上的改进
它与最短路径增值算法不同之处是:在Dinic算法中,我们用一个dfs过程代替多次bfs来寻找阻塞流。下面给出其算法步骤:
算法流程:
以上转自http://blog.csdn.net/pi9nc/article/details/23339111
#include <queue>
#include <cstdio>
#include <vector>
#include <cstring>
using namespace std;
typedef int Type;
const int MAXNODE = 210;
const int MAXEDGE = 10010;
const Type INF = 0x3f3f3f3f;
struct Edge
{
int u, v, next;
Type cap, flow;
Edge() {}
Edge(int u, int v, Type cap, Type flow, int next): u(u), v(v), cap(cap), flow(flow), next(next) {}
};
struct Dinic
{
int n, m, s, t;
Edge edges[MAXNODE];
int head[MAXNODE];
int cur[MAXNODE], d[MAXNODE];
bool vis[MAXNODE];
vector<int> cut;
void init(int n)
{
this->n=n;
memset(head, -1, sizeof(head));
m=0;
}
void addEdge(int u, int v, Type cap)
{
edges[m]=Edge(u, v, cap, 0, head[u]);
head[u]=m++;
edges[m]=Edge(v, u, 0, 0, head[v]);
head[v]=m++;
}
//bfs构建层次图;
bool bfs()
{
memset(vis, 0, sizeof(vis));
queue<int> Q;
Q.push(s);
d[s]=0;
vis[s]=1;
while(!Q.empty())
{
int u=Q.front(); Q.pop();
for(int i=head[u]; i!=-1; i=edges[i].next)
{
Edge &e=edges[i];
if(!vis[e.v] && e.cap > e.flow)
{
vis[e.v]=true;
d[e.v]=d[u]+1;
Q.push(e.v);
}
}
}
return vis[t];
}
Type dfs(int u, Type a)
{
if(u==t || a==0) return a;
Type flow=0, f;
for(int i=cur[u]; ~i; i=edges[i].next)
{
Edge &e=edges[i];
if(d[u]+1==d[e.v] && (f = dfs(e.v, min(a, e.cap-e.flow))) > 0)
{
e.flow += f;
edges[i ^ 1].flow -= f;
flow += f;
a -= f;
if(a==0) break;
}
}
return flow;
}
Type maxFlow(int s, int t)
{
this->s=s; this->t=t;
Type flow=0;
while(bfs())
{
//cur[i]; 表示第i个点已经增广到哪一条边了, 相当于一个剪枝;
for(int i=0; i<n; i++)
cur[i]=head[i];
flow += dfs(s, INF);
}
return flow;
}
}dinic;
int main()
{
return 0;
}
浙公网安备 33010602011771号