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 150 151 152 153 154 155 156 157 158 159 160 161
| #include <bits/stdc++.h>
using namespace std;
typedef long long ll; typedef pair<int, int> pii; #define INFLL 0x3f3f3f3f3f3f3f3f #define N 20010
int n, m;
struct Dicnic { struct Edge { int to, nxt; ll flow;
Edge() {} Edge(int to, int nxt, ll flow) : to(to), nxt(nxt), flow(flow) {} } edge[N << 1]; int head[N], tot; int dep[N]; void Init() { memset(head, -1, sizeof head); tot = 0; } void addedge(int u, int v, int w, int rw = 0) { edge[tot] = Edge(v, head[u], w); head[u] = tot++; edge[tot] = Edge(u, head[v], rw); head[v] = tot++; } bool BFS() { memset(dep, -1, sizeof dep); queue<int> q; q.push(1); dep[1] = 1; while (!q.empty()) { int u = q.front(); q.pop(); for (int i = head[u]; ~i; i = edge[i].nxt) { if (edge[i].flow && dep[edge[i].to] == -1) { dep[edge[i].to] = dep[u] + 1; q.push(edge[i].to); } } } return dep[n] >= 0; } ll DFS(int u, ll f) { if (u == n || f == 0) return f; ll w, used = 0; for (int i = head[u]; ~i; i = edge[i].nxt) { if (edge[i].flow && dep[edge[i].to] == dep[u] + 1) { w = DFS(edge[i].to, min(f - used, edge[i].flow)); edge[i].flow -= w; edge[i ^ 1].flow += w; used += w; if (used == f) return f; } } if (!used) dep[u] = -1; return used; } ll solve() { ll ans = 0; while (BFS()) { ans += DFS(1, INFLL); } return ans; } } dicnic;
struct Edge { int u, to, nxt, w;
Edge() {} Edge(int u, int to, int nxt, int w) : u(u), to(to), nxt(nxt), w(w) {}
} edge[N << 1];
struct qnode { int u; ll w;
qnode() {} qnode(int u, ll w) : u(u), w(w) {} bool operator<(const qnode &other) const { return w > other.w; } };
int head[N], tot; ll dis[N];
void Init() { memset(dis, 0x3f, sizeof dis); memset(head, -1, sizeof head); tot = 0; }
void addedge(int u, int v, ll w) { edge[tot] = Edge(u, v, head[u], w); head[u] = tot++; }
void Dijkstra() { priority_queue<qnode> q; q.push(qnode(1, 0)); dis[1] = 0ll; while (!q.empty()) { int u = q.top().u; q.pop(); for (int i = head[u]; ~i; i = edge[i].nxt) { int v = edge[i].to; ll w = edge[i].w; if (dis[v] > dis[u] + w) { dis[v] = dis[u] + w; q.push(qnode(v, dis[v])); } } } }
int main() {
int T; scanf("%d", &T); while (T--) { scanf("%d %d", &n, &m); Init(); for (int i = 1, u, v, w; i <= m; ++i) { scanf("%d %d %d", &u, &v, &w); addedge(u, v, w); } Dijkstra(); dicnic.Init(); for (int i = 0; i < tot; ++i) { int u = edge[i].u; int v = edge[i].to; ll w = edge[i].w; if (dis[v] == dis[u] + w) { dicnic.addedge(u, v, w); } } printf("%lld\n", dicnic.solve()); } return 0; }
|