-
Notifications
You must be signed in to change notification settings - Fork 0
/
dinic.cpp
138 lines (136 loc) · 2.93 KB
/
dinic.cpp
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
struct Dinic{
vi ans;
struct Edge{
int to;
int rev;
int flo;
int cap;
Edge(){}
Edge(int _to,int _rev,int _flo,int _cap):to(_to),rev(_rev),flo(_flo),cap(_cap){}
};
vector <vector<Edge> > adj;
int src,dest;
int n;
vi ind;
vi level;
Dinic(){}
Dinic(int _n,int _src,int _dest)
{
n=_n;
src = _src;
dest= _dest;
adj.resize(n);
ind.resize(n);
level.resize(n);
}
void addEdge(int u,int v,int cap,int rcap=0)
{
Edge x,y;
x = Edge(v,adj[v].Z,0,cap);
y = Edge(u,adj[u].Z,0,rcap);
adj[u].PB(x);
adj[v].PB(y);
}
bool bfs()
{
queue<int> kyou;
REP(i,0,n)
{
level[i]=-1;
ind[i]=0;
}
level[src]=0;
kyou.push(src);
while(kyou.Z)
{
int frt = kyou.front();
kyou.pop();
for(Edge z : adj[frt])
{
if (level[z.to]<0&&z.flo<z.cap)
{
level[z.to]=level[frt]+1;
kyou.push(z.to);
}
}
}
return level[dest]!=-1;
}
bool bfs2()
{
queue<int> kyou;
REP(i,0,n)
{
level[i]=-1;
ind[i]=0;
}
level[src]=0;
kyou.push(src);
while(kyou.Z)
{
int frt = kyou.front();
kyou.pop();
for(Edge z : adj[frt])
{
if (level[z.to]<0&&z.flo==z.cap)
{
level[z.to]=level[frt]+1;
kyou.push(z.to);
}
}
}
return level[dest]!=-1;
}
int dfs(int x,int flo)
{
if(x==dest)
return flo;
for(;ind[x]<adj[x].Z;ind[x]++)
{
Edge &xx = adj[x][ind[x]];
if(level[xx.to]!=level[x]+1 || xx.cap==xx.flo)continue;
int fl = dfs(xx.to,min(flo,xx.cap-xx.flo));
if (fl!=0)
{
xx.flo+=fl;adj[xx.to][xx.rev].flo-=fl;
return fl;
}
}
return 0;
}
int dfs1(int x)
{
if(x==dest)
{
ans.PB(x);
return 1;
}
for(;ind[x]<adj[x].Z;ind[x]++)
{
Edge &xx = adj[x][ind[x]];
if(level[xx.to]!=level[x]+1 || xx.flo <= 0)continue;
int fl = dfs1(xx.to);
if (fl=1)
{
xx.flo=0;
ans.PB(x);
return 1;
}
}
return 0;
}
int maxFlow()
{
int ans = 0;
while(bfs())
{
for(int fl = dfs(src,1e9);fl>0;fl=dfs(src,1e9))
{
trace(fl);
trace("RE");
ans+=fl;
}
}
return ans;
}
};