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
| #include <cstdio> #include <algorithm> #include <vector> using namespace std; const int N = 5e4 + 10, M = 1e5 + 10; int n, m, s, p[N]; struct Edge { int u, v, w; bool operator<(const Edge &_) const { return w < _.w; } }; vector<Edge> e[2]; int fa(int x) { return x == p[x] ? x : p[x] = fa(p[x]); } bool add(Edge x) { if (fa(x.u) == fa(x.v)) return false; p[p[x.u]] = p[x.v]; return true; } int main() { scanf("%d%d%d", &n, &m, &s); for (int u, v, w, c; m; m--) { scanf("%d%d%d%d", &u, &v, &w, &c); e[c].push_back((Edge){u, v, w}); } sort(e[0].begin(), e[0].end()); sort(e[1].begin(), e[1].end()); int l = -100, r = 100; while (l < r) { int mid = l + r + 1 >> 1; for (int i = 0; i < n; i++) p[i] = i; int x = 0, y = 0, ans = 0; while (x < e[0].size() && y < e[1].size()) e[0][x].w + mid <= e[1][y].w ? ans += add(e[0][x++]) : add(e[1][y++]); while (x < e[0].size()) ans += add(e[0][x++]); ans < s ? r = mid - 1 : l = mid; } for (int i = 0; i < n; i++) p[i] = i; int x = 0, y = 0, ans = 0; while (x < e[0].size() && y < e[1].size()) if (e[0][x].w + l <= e[1][y].w) ans += (e[0][x].w + l) * add(e[0][x]), x++; else ans += e[1][y].w * add(e[1][y]), y++; while (x < e[0].size()) ans += (e[0][x].w + l) * add(e[0][x]), x++; while (y < e[1].size()) ans += e[1][y].w * add(e[1][y]), y++; printf("%d\n", ans - s * l); return 0; }
|