-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDinic.cpp
More file actions
149 lines (135 loc) · 3.44 KB
/
Dinic.cpp
File metadata and controls
149 lines (135 loc) · 3.44 KB
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
138
139
140
141
142
143
144
145
146
147
148
149
// Dinic法:最小カット,最大フローで使う
// 使い方: Dinic* dinic = new Dinic(V)で初期化(Vは頂点数)
// dinic->add_edgeまたはdinic->add_edge_bothで点をつなげてdinic->max_flowで最大フローを求める
#define NG -1
#define SZ(a) ((int)((a).size()))
class Dinic
{
public:
Dinic(int input_maxv) : maxv(input_maxv)
{
G.resize(input_maxv);
level.resize(input_maxv);
iter.resize(input_maxv);
}
void add_edge_both(int from, int to, int cap)
{
const int rev_from = SZ(G[from]);
const int rev_to = SZ(G[to]);
G[from].push_back(edge(to,cap,rev_to));
G[to].push_back(edge(from,cap,rev_from));
}
void add_edge(int from, int to, int cap)
{
const int rev_from = SZ(G[from]);
const int rev_to = SZ(G[to]);
G[from].push_back(edge(to,cap,rev_to));
G[to].push_back(edge(from,0,rev_from));
}
int max_flow(int s, int t)
{
int flow = 0;
for(;;)
{
bfs(s);
if(level[t]<0) break;
fill(iter.begin(),iter.end(),0);
int f;
while( (f=dfs(s,t,DINIC_INF))>0)
{
flow += f;
}
}
return flow;
}
vector <bool> get_nodes_in_group(int s)
{
vector <bool> ret(maxv);
queue<int> que;
que.push(s);
while(!que.empty())
{
int v = que.front();
que.pop();
ret[v]=true;
for(int i=0;i<SZ(G[v]);i++)
{
edge &e = G[v][i];
if(e.cap>0 && !ret[e.to])
{
que.push(e.to);
}
}
}
return ret;
}
void disp()
{
for (int v = 0; v < maxv; v++)
{
printf("%d:",v);
for(int i=0;i<SZ(G[v]);i++)
{
if(G[v][i].init_cap>0)
{
printf("->%d(%d),",G[v][i].to,G[v][i].init_cap);
}
}
printf("\n");
}
}
private:
void bfs(int s)
{
fill(level.begin(),level.end(),NG);
queue<int> que;
level[s]=0;
que.push(s);
while(!que.empty())
{
int v = que.front();
que.pop();
for(int i=0;i<SZ(G[v]);i++)
{
edge &e = G[v][i];
if(e.cap>0 && level[e.to]<0)
{
level[e.to] = level[v] + 1;
que.push(e.to);
}
}
}
}
int dfs(int v, int t, int f)
{
if(v==t) return f;
for (int &i=iter[v];i<SZ(G[v]);i++)
{
edge& e = G[v][i];
if(e.cap>0 && level[v]<level[e.to])
{
int d = dfs(e.to, t, min(f, e.cap));
if(d>0)
{
e.cap -= d;
G[e.to][e.rev].cap += d;
return d;
}
}
}
return 0;
}
static const int DINIC_INF = INT_MAX;
struct edge
{
edge(int input_to, int input_cap, int input_rev) : to(input_to), cap(input_cap), rev(input_rev), init_cap(input_cap) {}
int to;
int cap;
int rev;
int init_cap;
};
int maxv;
vector < vector <edge> > G;
vector < int > level;
vector < int > iter;
};