#ifndef CHIKA_DINIC_HPP #define CHIKA_DINIC_HPP #include #include #include #include #include template class Dinic { private: struct E { int to, rev; Cap cap; }; int n, ed; std::vector> G; std::vector lv, idx; std::vector> inv; bool BFS(int st) { lv.assign(n, -1); std::queue bfs; bfs.push(st); lv[st] = 0; while (not bfs.empty()) { int u = bfs.front(); bfs.pop(); for (auto e : G[u]) { if (e.cap <= 0 or lv[e.to] != -1) continue; bfs.push(e.to); lv[e.to] = lv[u] + 1; } } return lv[ed] != -1; } Cap DFS(int u, Cap f) { if (u == ed) return f; Cap ret = 0; for (int &i = idx[u]; i < int(G[u].size()); ++i) { auto &e = G[u][i]; if (e.cap <= 0 or lv[e.to] != lv[u] + 1) continue; Cap nf = DFS(e.to, std::min(f, e.cap)); ret += nf; e.cap -= nf; f -= nf; G[e.to][e.rev].cap += nf; if (f == 0) return ret; } if (ret == 0) lv[u] = -1; return ret; } public: Dinic(int n_) : n(n_), G(n) {} void add_edge(int u, int v, Cap c) { G[u].push_back({v, int(G[v].size()), c}); G[v].push_back({u, int(G[u].size()) - 1, 0}); inv.emplace_back(v, int(G[v].size()) - 1); } Cap operator()(int st, int ed_) { ed = ed_; Cap ret = 0; while (BFS(st)) { idx.assign(n, 0); Cap f = DFS(st, std::numeric_limits::max()); ret += f; if (f == 0) break; } return ret; } Cap operator[](int i) const { return G[inv[i].first][inv[i].second].cap; } std::vector get_visible(int s) const { std::vector vis(n); std::queue bfs; bfs.push(s); vis[s] = true; while (not bfs.empty()) { int u = bfs.front(); bfs.pop(); for (auto e : G[u]) { if (vis[e.to] or e.cap == 0) continue; bfs.push(e.to); vis[e.to] = true; } } return vis; } }; #endif // CHIKA_DINIC_HPP #include using namespace std; constexpr int kInf = 1 << 30; int main() { cin.tie(nullptr)->sync_with_stdio(false); int n, m, k; cin >> n >> m >> k; vector> e(m); for (auto &[u, v, c, d] : e) cin >> u >> v >> c >> d; sort(e.begin(), e.end(), [](const auto &lhs, const auto &rhs) { return get<2>(lhs) < get<2>(rhs); }); vector y(m); for (int i = 0; i < m; ++i) { auto [u, v, c, d] = e[i]; const int S = 0, T = n + 1; Dinic flow(n + 2); for (int j = 0; j < m; ++j) { if (i == j) continue; auto [uj, vj, _, __] = e[j]; flow.add_edge(S, uj, y[j]); flow.add_edge(uj, vj, y[j]); } for (int j = 1; j <= n; ++j) { if (j == u or j == v) continue; flow.add_edge(j, T, k); } y[i] = flow(S, T) + k - accumulate(y.begin(), y.end(), 0LL); y[i] = min(y[i], d); } if (accumulate(y.begin(), y.end(), 0LL) != 1LL * k * (n - 1)) { cout << "-1\n"; return 0; } int64_t ans = 0; for (int i = 0; i < m; ++i) ans += y[i] * get<2>(e[i]); cout << ans << '\n'; return 0; }