一个朴素的想法是跑
n2
次最大流,但是这样啃腚会TLE。现在介绍一种分治法:
1、任意选两个点作为源点和汇点,求出最小割,记最小割容量为
ans
。
2、这个最小割把图分成了两个集合,源点属于其中一个集合,汇点属于另一个。
3、对于一对点
u,v
,如果它们属于不同的集合,则用
ans
更新
u,v
之间的最小割。
4、对源点所属的集合和汇点所属的集合继续递归。
这样,就只需要跑
O(n)
次最大流。
代码:
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
inline int read() {
int res = 0; bool bo = 0; char c;
while (((c = getchar()) < '0' || c > '9') && c != '-');
if (c == '-') bo = 1; else res = c - 48;
while ((c = getchar()) >= '0' && c <= '9')
res = (res << 3) + (res << 1) + (c - 48);
return bo ? ~res + 1 : res;
}
const int N = 153, M = 3e5 + 5, INF = 0x3f3f3f3f;
int n, m, ecnt, nxt[M], adj[N], go[M], cap[M], Cap[M], ans[N][N], len, que[N],
S, T, lev[N], a[N], t1[N], t2[N], Q;
bool vis[N];
void add_edge(int u, int v, int w) {
nxt[++ecnt] = adj[u]; adj[u] = ecnt; go[ecnt] = v; cap[ecnt] = w;
nxt[++ecnt] = adj[v]; adj[v] = ecnt; go[ecnt] = u; cap[ecnt] = w;
}
bool bfs() {
int i; for (i = 1; i <= n; i++) lev[i] = -1;
lev[que[len = 1] = S] = 0;
for (i = 1; i <= len; i++) {
int u = que[i];
for (int e = adj[u], v; e; e = nxt[e])
if (cap[e] > 0 && lev[v = go[e]] == -1) {
lev[que[++len] = v] = lev[u] + 1;
if (v == T) return 1;
}
}
return 0;
}
int dinic(int u, int flow) {
if (u == T) return flow;
int res = 0, delta;
for (int e = adj[u], v; e; e = nxt[e])
if (cap[e] > 0 && lev[u] < lev[v = go[e]]) {
delta = dinic(v, min(cap[e], flow - res));
if (delta) {
cap[e] -= delta; cap[e ^ 1] += delta; res += delta;
if (res == flow) break;
}
}
if (res != flow) lev[u] = -1;
return res;
}
int solve() {
int ans = 0;
while (bfs()) ans += dinic(S, INF);
return ans;
}
void dfs(int u) {
vis[u] = 1;
for (int e = adj[u], v; e; e = nxt[e])
if (cap[e] > 0 && !vis[v = go[e]]) dfs(v);
}
void orzpyz(int l, int r) {
int i, j, n1, n2; if (l == r) return;
for (i = 2; i <= ecnt; i++) cap[i] = Cap[i]; S = a[l]; T = a[r];
int orz = solve(); for (i = 1; i <= n; i++) vis[i] = 0; dfs(S);
n1 = n2 = 0; for (i = l; i <= r; i++) {
(vis[a[i]] ? t1[++n1] : t2[++n2]) = a[i];
}
for (i = 1; i <= n; i++) for (j = 1; j <= n; j++)
if (vis[i] ^ vis[j]) ans[i][j] = min(ans[i][j], orz);
for (i = l; i <= l + n1 - 1; i++) a[i] = t1[i - l + 1];
for (i = r - n2 + 1; i <= r; i++) a[i] = t2[i - r + n2];
orzpyz(l, l + n1 - 1); orzpyz(r - n2 + 1, r);
}
void work() {
int i, j, x, y, z; n = read(); ecnt = 1; m = read();
for (i = 1; i <= n; i++) for (j = 1; j <= n; j++) ans[i][j] = INF;
for (i = 1; i <= n; i++) adj[i] = 0, a[i] = i;
for (i = 1; i <= m; i++) x = read(), y = read(), z = read(),
add_edge(x, y, z);
for (i = 2; i <= ecnt; i++) Cap[i] = cap[i]; Q = read(); orzpyz(1, n);
while (Q--) {
x = read(); y = 0; for (i = 1; i <= n; i++) for (j = i + 1; j <= n; j++)
if (ans[i][j] <= x) y++; printf("%d\n", y);
}
printf("\n");
}
int main() {
int T = read(); while (T--) work();
return 0;
}