-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraph.cc
More file actions
109 lines (109 loc) · 2.96 KB
/
graph.cc
File metadata and controls
109 lines (109 loc) · 2.96 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
class Graph {
typedef pair<int, int> P;
int V;
struct edge { int to, cap, cost, rev; };
vector<vector<edge> > G;
vector<bool> used;
int dfs(int v, int f) {
if(v == sink) return f;
used[v] = true;
for(int i = 0; i < G[v].size(); i++) {
edge &e = G[v][i];
if(!used[e.to] && e.cap > 0) {
int d = dfs(e.to, min(f, e.cap));
if(d > 0) {
e.cap -= d;
G[e.to][e.rev].cap += d;
return d;
}
}
}
return 0;
}
public:
int source, sink;
Graph() { V = 0; source = addVertex(); sink = addVertex(); }
int addVertex() {
G.resize(V+1);
return V++;
}
void addEdge(int from, int to, int cap, int cost = 0) {
G[from].push_back((edge){to, cap, cost, (int)G[to].size()});
G[to].push_back((edge){from, 0, -cost, (int)G[from].size() - 1});
}
int maxFlow() {
int flow = 0;
while(true) {
used.resize(V);
fill(used.begin(), used.end(), false);
int f = dfs(source, 1e9);
if(f == 0) return flow;
flow += f;
}
}
pair<int,int> minCostFlow(int f=2e9, bool BellmanFord=false) {
int res = 0;
vector<int> h(V), prevv(V), preve(V);
while(f > 0) {
vector<int> dist(V, 1e9);
dist[source] = 0;
if(BellmanFord) {
BellmanFord = false;
bool update = true;
while(update) {
update = false;
for(int v = 0; v < V; v++) {
if(dist[v] == 1e9) continue;
for(int i = 0; i < G[v].size(); i++) {
edge &e = G[v][i];
if(e.cap > 0 && dist[e.to] > dist[v] + e.cost) {
dist[e.to] = dist[v] + e.cost;
prevv[e.to] = v;
preve[e.to] = i;
update = true;
}
}
}
}
} else {
priority_queue<P, vector<P>, greater<P> > que;
que.push(P(0, source));
while(!que.empty()) {
P p = que.top(); que.pop();
int v = p.second;
if(dist[v] < p.first) continue;
for(int i = 0; i < G[v].size(); i++) {
edge &e = G[v][i];
if(e.cap > 0 && dist[e.to] > dist[v] + e.cost + h[v] - h[e.to]) {
dist[e.to] = dist[v] + e.cost + h[v] - h[e.to];
prevv[e.to] = v;
preve[e.to] = i;
que.push(P(dist[e.to], e.to));
}
}
}
}
if(dist[sink] == 1e9) {
if(f > 1e9) return P(res, 2e9 - f);
else return P(1e9, 0);
}
for(int v = 0; v < V; v++) {
if(h[v] >= 1e9 || dist[v] >= 1e9)
h[v] = 1e9;
else
h[v] += dist[v];
}
int d = f;
for(int v = sink; v != source; v = prevv[v])
d = min(d, G[prevv[v]][preve[v]].cap);
f -= d;
res += d * h[sink];
for(int v = sink; v != source; v = prevv[v]) {
edge &e = G[prevv[v]][preve[v]];
e.cap -= d;
G[v][e.rev].cap += d;
}
}
return P(res, f);
}
};