-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy path4174.cpp
96 lines (96 loc) · 2.03 KB
/
4174.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
#include <algorithm>
#include <cstdio>
#include <cstring>
int read() {
int res = 0, c;
do
c = getchar();
while(c < '0' || c > '9');
while('0' <= c && c <= '9') {
res = res * 10 + c - '0';
c = getchar();
}
return res;
}
const int size = 55005, S = 0;
int T;
struct Edge {
int to, nxt, f;
} E[6 * size];
int last[size] = {}, cnt = 1;
void addEdgeImpl(int u, int v, int f) {
++cnt;
E[cnt].to = v, E[cnt].nxt = last[u], E[cnt].f = f;
last[u] = cnt;
}
void addEdge(int u, int v, int f) {
addEdgeImpl(u, v, f);
addEdgeImpl(v, u, 0);
}
const int inf = 1 << 30;
int d[size], q[size];
bool BFS(int siz) {
memset(d, 0, sizeof(int) * siz);
int b = 0, e = 1;
q[0] = S;
d[S] = 1;
while(b != e) {
int u = q[b++];
for(int i = last[u]; i; i = E[i].nxt) {
int v = E[i].to;
if(E[i].f && d[v] == 0) {
d[v] = d[u] + 1;
q[e++] = v;
}
}
}
return d[T];
}
int now[size];
int DFS(int u, int f) {
if(u == T || f == 0)
return f;
int res = 0, k;
for(int& i = now[u]; i; i = E[i].nxt) {
int v = E[i].to;
if(d[v] == d[u] + 1 &&
(k = DFS(v, std::min(E[i].f, f)))) {
E[i].f -= k;
E[i ^ 1].f += k;
f -= k;
res += k;
if(f == 0)
break;
}
}
if(res == 0)
d[u] = -1;
return res;
}
int dinic(int siz) {
int res = 0;
while(BFS(siz)) {
memcpy(now, last, sizeof(int) * siz);
res += DFS(S, inf);
}
return res;
}
int main() {
int n = read();
int m = read();
T = n + m + 1;
for(int i = 1; i <= n; ++i)
addEdge(i, T, read());
int tot = 0;
for(int i = 1; i <= m; ++i) {
int a = read();
int b = read();
int c = read();
tot += c;
addEdge(S, i + n, c);
addEdge(i + n, a, inf);
addEdge(i + n, b, inf);
}
printf("%d\n", tot - dinic(T + 1));
return 0;
}