最大流模版Dinic算法

时间:2021-05-11 19:26:22

网络流的算法有很多, 最基础的为EK算法, 他的时间复杂度为o(n*m^2), Dinic算法的时间复杂为O(m*n^2),Dinic算法是现构造层次图,然后用阻塞流来增广。构造层次图有一个bfs, 增广是用dfs来写。

详细的讲述请参考 刘汝佳写的《算法竞赛入门经典训练指南》 (大白书)

#include<stdio.h>
#include<string.h>
#include<queue>
#include<vector>
#include<algorithm>
using namespace std;
const int maxn = 1000 + 10;
const int INF = 0x3f3f3f3f;
struct Edge
{
int from, to, cap, flow;
Edge(int u, int v, int c, int f) : from(u), to(v), cap(c), flow(f) {}
};
struct Dinic
{
int n, m, s, t;
vector<int> G[maxn];
vector<Edge> edges;
bool vis[maxn];
int d[maxn], cur[maxn];
void inin(int n)
{
this->n = 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));
m = edges.size();
G[from].push_back(m-2);
G[to].push_back(m-1);
}
bool bfs()
{
memset(vis, false, sizeof(vis));
queue<int> Q;
d[s] = 0;
Q.push(s);
vis[s] = true;
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)
{
d[e.to] = d[x] + 1;
Q.push(e.to);
vis[e.to] = true;
}
}
}
return vis[t];
}
int dfs(int x, int a)
{
if(x==t || a==0)
return a;
int f, flow = 0;
for(int& i = cur[x]; i < G[x].size(); i++)
{
Edge& e = edges[G[x][i]];
if(d[e.to]==d[x]+1 && (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 max_flow(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;
}
};
Dinic solve;
int main()
{
int n, m;
while(~scanf("%d%d", &m, &n))
{
solve.inin(n);
while(m--)
{
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
solve.AddEdge(a, b, c);
}
printf("%d\n", solve.max_flow(1, n));
}
return 0;
}