网络流

Author Avatar
Axell Aug 17, 2019
  • Read this article on other devices

最大流

dinic算法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
struct node{
int Next,y,v;
}Pth[880005];
int tot=1,head[20005];
inline void add(int x,int y,int v){
Pth[++tot]={head[x],y,v};head[x]=tot;
Pth[++tot]={head[y],x,0};head[y]=tot;
}
int d[20005],S,T,INF=0x3f3f3f3f;
int qu[60005];
bool bfs(){
memset(d,0,sizeof d);
int l=0,r=0;
qu[++r]=S; d[S]=1;
while (l<r){
int x=qu[++l];
for (int i=head[x];i;i=Pth[i].Next){
int y=Pth[i].y;
if (!d[y] && Pth[i].v){
d[y]=d[x]+1;
qu[++r]=y;
if (y==T) return 1;
}
}
}
return 0;
}
int dinic(int x,int flow){
if (x==T) return flow;
int rest=flow,k;
for (int i=head[x];i&&rest;i=Pth[i].Next){
int y=Pth[i].y;
if (Pth[i].v && d[y]==d[x]+1){
k=dinic(y,min(rest,Pth[i].v));
if (!k) d[y]=0;
Pth[i].v-=k;
Pth[i^1].v+=k;
rest-=k;
}
}
return flow-rest;
}
ll solve(int s,int t){
ll flow,maxflow=0;
S=s,T=t;
while (bfs()){
while (flow=dinic(s,INF)) maxflow+=flow;
}
return maxflow;
}

Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.

Link to this article: https://blog.axell.top/archives/%E7%BD%91%E7%BB%9C%E6%B5%81/